package com.sailfish.springbootdemo.service.db1;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.common.RoleName;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db1.*;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.*;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.FileConverterUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

@Service
public class PcbaDeviceResourceServiceImpl implements PcbaDeviceResourceService {

    @Autowired
    private PcbaDeviceResourceDao pcbaDeviceResourceDao;

    @Autowired
    private PcbaDeviceRelatedDeviceParamDao pcbaDeviceRelatedDeviceParamDao;

    @Autowired
    private PcbaDeviceRelatedTechParamDao pcbaDeviceRelatedTechParamDao;

    @Autowired
    private PcbaDeviceRelatedTechParamActualDao pcbaDeviceRelatedTechParamActualDao;

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private BrandTypeDao brandTypeDao;

    @Autowired
    private PcbaDeviceTypeDao pcbaDeviceTypeDao;

    @Autowired
    private CoreAlgorithmService coreAlgorithmService;

    @Autowired
    private PcbaDeviceDao pcbaDeviceDao;

    @Autowired
    private PcbaLineDao pcbaLineDao;

    @Autowired
    private AuditRecordDao auditRecordDao;

    @Autowired
    private TechDeviceParamDao techDeviceParamDao;

    @Autowired
    private PcbaDeviceParamTypeDao pcbaDeviceParamTypeDao;

    @Autowired
    private TechDeviceParamTypeDao techDeviceParamTypeDao;

    @Autowired
    private PcbaFileDao pcbaFileDao;

    @Autowired
    private PcbaDeviceParamDao pcbaDeviceParamDao;

    @Autowired
    private FileGroupDao fileGroupDao;

    @Autowired
    private CommonJudgeCanDeleteService commonService;

    @Value("${personal.config.file.file-save-url}")
    private String fileSaveUrl;

    @Value("${personal.config.amazon-s3.url}")
    private String url;
    @Value("${personal.config.amazon-s3.file-bucket}")
    private String fileBucket;
    @Value("${personal.config.env}")
    private String env;

    @Qualifier("MysqlTransactionManager1")
    @Autowired
    private DataSourceTransactionManager transactionManager1;

    @Autowired
    private OperateService operateService;

    private String operateSmallType = "设备资源";

    @Override
    public Result getAllByDeviceTypeAndSearch(String searchValue, Integer pcbaDeviceTypeId, Integer pcbaDeviceResourceId, Integer isTechOwn, Integer status, Integer brandId, Integer brandTypeId, Integer auditStatusBase, Integer auditStatusTech, Integer page, Integer pageSize) {
        try {
            if (isTechOwn != null && isTechOwn != 1 && isTechOwn != 2) {
                return ResultUtil.error(500, "错误参数isTechOwn", "Error Param isTechOwn", null);
            }
            if (page == null || !CommonUtils.isNumeric(page.toString())) {
                return ResultUtil.error(500, "错误参数page", "Error Param page", null);
            }
            if (pageSize == null || !CommonUtils.isNumeric(pageSize.toString())) {
                return ResultUtil.error(500, "错误参数pageSize", "Error Param pageSize", null);
            }
            int begin = (page - 1) * pageSize;
            List<PcbaDeviceResource> list = pcbaDeviceResourceDao.getAllByDeviceTypeAndSearch(searchValue, pcbaDeviceTypeId, pcbaDeviceResourceId, isTechOwn, status, brandId, brandTypeId, begin, pageSize, null, auditStatusBase, auditStatusTech);
            for (PcbaDeviceResource pcbaDeviceResource : list) {
                /*if(pcbaDeviceResource.getPcbaDevicePicture() != null && !"".equals(pcbaDeviceResource.getPcbaDevicePicture())){
                    if("h3c_pro".equals(env)){
                        pcbaDeviceResource.setPcbaDevicePictureBase64(CommonUtils.base64Prefix() + CommonUtils.getImageBase64FromUrl(url + "/" + fileBucket + "/" + pcbaDeviceResource.getPcbaDevicePicture()));
                    }else{
                        pcbaDeviceResource.setPcbaDevicePictureBase64(CommonUtils.base64Prefix() + CommonUtils.getImageBase64FromUrl(CommonUtils.returnHostPrefixUrl() + pcbaDeviceResource.getPcbaDevicePicture()));
                    }
                }*/

                pcbaDeviceResource.setBrand(brandDao.getBrandById(pcbaDeviceResource.getBrandId()));
                pcbaDeviceResource.setBrandType(brandTypeDao.getBrandTypeByIdAndBrand(pcbaDeviceResource.getBrandTypeId(), pcbaDeviceResource.getBrandId()));
                pcbaDeviceResource.setPcbaDeviceType(pcbaDeviceTypeDao.getById(pcbaDeviceResource.getPcbaDeviceTypeId()));

                List<PcbaFile> pcbaFileList = pcbaFileDao.getPcbaFileByDeviceResourceId(pcbaDeviceResource.getPcbaDeviceResourceId());
                for (PcbaFile pcbaFile : pcbaFileList) {
                    pcbaFile.setFileGroup(fileGroupDao.getFileGroupById(pcbaFile.getFileGroupId()));
                }
                pcbaDeviceResource.setPcbaFileList(pcbaFileList);
            }
            List<PcbaDeviceResource> list2 = pcbaDeviceResourceDao.getAllByDeviceTypeAndSearch(searchValue, pcbaDeviceTypeId, pcbaDeviceResourceId, isTechOwn, status, brandId, brandTypeId, null, null, null, auditStatusBase, auditStatusTech);
            return ResultUtil.tableSuccess(page, pageSize, list2.size(), list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result getAllPcbaDeviceResource() {
        try {
            List<PcbaDeviceResource> list = pcbaDeviceResourceDao.getAllPcbaDeviceResource();
            for (PcbaDeviceResource pcbaDeviceResource : list) {
                pcbaDeviceResource.setPcbaDeviceType(pcbaDeviceTypeDao.getById(pcbaDeviceResource.getPcbaDeviceTypeId()));
                pcbaDeviceResource.setBrand(brandDao.getBrandById(pcbaDeviceResource.getBrandId()));
                pcbaDeviceResource.setBrandType(brandTypeDao.getBrandTypeByIdAndBrand(pcbaDeviceResource.getBrandTypeId(), pcbaDeviceResource.getBrandId()));
            }
            return ResultUtil.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result deleteById(Integer pcbaDeviceResourceId) {
        try {
            if (pcbaDeviceResourceId == null || "".equals(pcbaDeviceResourceId.toString())) {
                return ResultUtil.error(500, "缺少参数pcbaDeviceResourceId", "Miss Param pcbaDeviceResourceId", null);
            }

            String userId = UserHeaderHolder.getUserId();
            PcbaDeviceResource oldPcbaDeviceResource = pcbaDeviceResourceDao.getById(pcbaDeviceResourceId);

            // 设备资源删除判断 是否 有被应用，有应用到不允许删除
            Integer nums = commonService.judgeCanDeletePcbaDeviceResource(pcbaDeviceResourceId);
            if (nums > 0) {
                return ResultUtil.error(500, "禁止删除，线体已有" + nums + "处使用该设备资源", "Forbidden Delete", null);
            }
            //改为假删
            //            PcbaDeviceResource updatePcbaDeviceResource = new PcbaDeviceResource();
//            updatePcbaDeviceResource.setPcbaDeviceResourceId(pcbaDeviceResourceId);
//            updatePcbaDeviceResource.setStatus(2);
//            pcbaDeviceResourceDao.updatePcbaDeviceResource(updatePcbaDeviceResource);

            //真删
            pcbaDeviceResourceDao.deleteById(pcbaDeviceResourceId);
            //基线参数和工艺参数均不用删除
            pcbaDeviceRelatedDeviceParamDao.deleteDeviceRelatedParam(pcbaDeviceResourceId);
            pcbaDeviceRelatedTechParamDao.deleteDeviceRelatedParam(pcbaDeviceResourceId);

            // 操作日志
            //operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldPcbaDeviceResource), JSONObject.toJSONString(updatePcbaDeviceResource)));
            operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 2, 1, new Date(), JSONObject.toJSONString(oldPcbaDeviceResource), null));

            return ResultUtil.success(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    //@Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result addOrUpdateDeviceAndParamRelated(String data) {
        try {
            String userId = UserHeaderHolder.getUserId();
            Date d = new Date();
            JSONObject jsonObject = JSONObject.parseObject(data);
            String mode = jsonObject.getString("mode");
            JSONArray jsonArray = jsonObject.getJSONArray("pcbaDeviceRelatedDeviceParamList");

            if ("add".equals(mode)) {
                // 新增pcbaDevice
                // 设备类型 + 品牌 + 型号 + 备注  确定唯一性
                Integer pcbaDeviceTypeId = Integer.parseInt(jsonObject.get("pcbaDeviceTypeId").toString());
                Integer brandId = Integer.parseInt(jsonObject.get("brand").toString());
                Integer brandTypeId = Integer.parseInt(jsonObject.get("type").toString());
                String notes = jsonObject.get("notes").toString();
                PcbaDeviceResource judgeUniquePcbaDeviceResource;
                if (notes == null || "".equals(notes)) {
                    judgeUniquePcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsWithoutNotes(pcbaDeviceTypeId, brandId, brandTypeId, null);
                } else {
                    judgeUniquePcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsJudgeUnique(pcbaDeviceTypeId, brandId, brandTypeId, notes, null);
                }
                if (judgeUniquePcbaDeviceResource != null) {
                    return ResultUtil.error(500, "当前已存在相同的 设备类型 + 品牌 + 型号 + 备注 ", "Already Exist Same Kind", null);
                }

                PcbaDeviceResource pcbaDeviceResource = new PcbaDeviceResource();
                pcbaDeviceResource.setBrandId(brandId);
                pcbaDeviceResource.setBrandTypeId(brandTypeId);
                pcbaDeviceResource.setStatus(Integer.parseInt(jsonObject.getString("status")));
                pcbaDeviceResource.setSort(Integer.parseInt(jsonObject.getString("sort")));
                pcbaDeviceResource.setNotes(notes);
                pcbaDeviceResource.setPcbaDevicePicture(jsonObject.getString("pcbaDevicePicture"));
                pcbaDeviceResource.setPicLength(jsonObject.get("picLength") != null && !"".equals(jsonObject.get("picLength").toString()) ? Integer.parseInt(jsonObject.getString("picLength")) : 0);
                pcbaDeviceResource.setPicWidth(jsonObject.get("picWidth") != null && !"".equals(jsonObject.get("picWidth").toString()) ? Integer.parseInt(jsonObject.getString("picWidth")) : 0);
                pcbaDeviceResource.setArchivesLink(jsonObject.getString("archivesLink"));
                pcbaDeviceResource.setPcbaDeviceTypeId(pcbaDeviceTypeId);
                pcbaDeviceResource.setCreateTime(d);
                pcbaDeviceResource.setIsFilledBaseParams(1);
                pcbaDeviceResource.setAuditStatusBase(jsonObject.get("auditStatusBase") != null && !"".equals(jsonObject.get("auditStatusBase").toString()) ? Integer.parseInt(jsonObject.getString("auditStatusBase")) : null);
                pcbaDeviceResource.setSubmitterBase(Integer.parseInt(userId));
                pcbaDeviceResource.setAuditorBase(4);
                pcbaDeviceResource.setAuditorTech(4);
                pcbaDeviceResourceDao.addPcbaDeviceResource(pcbaDeviceResource);

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(pcbaDeviceResource)));


                List<PcbaDeviceRelatedDeviceParam> list = new ArrayList<>();
                // 新增pcbaDeviceRelatedDeviceParam
                for (int a = 0; a < jsonArray.size(); a++) {
                    JSONObject jo = (JSONObject) jsonArray.get(a);
                    PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam = new PcbaDeviceRelatedDeviceParam();
                    pcbaDeviceRelatedDeviceParam.setCreateTime(d);
                    // 获取上面自增的id
                    pcbaDeviceRelatedDeviceParam.setPcbaDeviceResourceId(pcbaDeviceResource.getPcbaDeviceResourceId());
                    pcbaDeviceRelatedDeviceParam.setCreateTime(d);
                    pcbaDeviceRelatedDeviceParam.setPcbaDeviceParamKey(jo.get("pcbaDeviceParamKey").toString());
                    pcbaDeviceRelatedDeviceParam.setPcbaDeviceTypeId(Integer.parseInt(jo.get("pcbaDeviceTypeId").toString()));
                    pcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValue(jo.get("pcbaDeviceParamValue").toString());
                    pcbaDeviceRelatedDeviceParamDao.addDeviceRelatedParam(pcbaDeviceRelatedDeviceParam);

                    list.add(pcbaDeviceRelatedDeviceParam);
                }

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(list)));

                return ResultUtil.success(null);
            } else if ("update".equals(mode)) {
                Integer pcbaDeviceResourceId = jsonObject.getInteger("pcbaDeviceResourceId");
                if (pcbaDeviceResourceId == null || "".equals(pcbaDeviceResourceId.toString())) {
                    return ResultUtil.error(500, "缺少参数pcbaDeviceResourceId", "Miss Param pcbaDeviceResourceId", null);
                }

                Integer pcbaDeviceTypeId = Integer.parseInt(jsonObject.get("pcbaDeviceTypeId").toString());
                Integer brandId = Integer.parseInt(jsonObject.get("brand").toString());
                Integer brandTypeId = Integer.parseInt(jsonObject.get("type").toString());
                String notes = jsonObject.get("notes").toString();

                PcbaDeviceResource judgeUniquePcbaDeviceResource;
                if (notes == null || "".equals(notes)) {
                    judgeUniquePcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsWithoutNotes(pcbaDeviceTypeId, brandId, brandTypeId, pcbaDeviceResourceId);
                } else {
                    judgeUniquePcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsJudgeUnique(pcbaDeviceTypeId, brandId, brandTypeId, notes, pcbaDeviceResourceId);
                }

                if (judgeUniquePcbaDeviceResource != null) {
                    return ResultUtil.error(500, "当前已存在相同的 设备类型 + 品牌 + 型号 + 备注 ", "Already Exist Same Kind", null);
                }

                PcbaDeviceResource oldPcbaDeviceResource = pcbaDeviceResourceDao.getById(pcbaDeviceResourceId);

                // 获取原先的 基线参数
                List<PcbaDeviceRelatedDeviceParam> oldPcbaDeviceRelatedDeviceParamList = pcbaDeviceRelatedDeviceParamDao.getAllByDeviceResourceId(pcbaDeviceResourceId);

                /*Boolean isChangeParams = false;
                // 先判断池子key是否都存在
                List<String> oldKeyList = new ArrayList<>();
                for (PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam : oldPcbaDeviceRelatedDeviceParamList) {
                    String pcbaDeviceParamKey2 = pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamKey();
                    oldKeyList.add(pcbaDeviceParamKey2);
                }
                for(int a = 0;a<jsonArray.size();a++){
                    JSONObject jo = (JSONObject)jsonArray.get(a);
                    String pcbaDeviceParamKey1 = jo.getString("pcbaDeviceParamKey");
                    if(!oldKeyList.toString().contains(pcbaDeviceParamKey1)){
                        isChangeParams = true;
                        break;
                    }
                }
                // 再判断 参数是否发生变化
                for(int a = 0;a<jsonArray.size();a++){
                    JSONObject jo = (JSONObject)jsonArray.get(a);
                    String pcbaDeviceParamKey1 = jo.getString("pcbaDeviceParamKey");
                    String pcbaDeviceParamValue1 = jo.getString("pcbaDeviceParamValue");
                    for (PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam : oldPcbaDeviceRelatedDeviceParamList) {
                        String pcbaDeviceParamKey2 = pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamKey();
                        String pcbaDeviceParamValue2 = pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValue();
                        if(pcbaDeviceParamKey1.equals(pcbaDeviceParamKey2) && !pcbaDeviceParamValue1.equals(pcbaDeviceParamValue2)){
                            isChangeParams = true;
                            break;
                        }
                    }
                }*/

                List<JSONObject> changeList = new ArrayList<>();
                for (int a = 0; a < jsonArray.size(); a++) {
                    JSONObject jo = jsonArray.getJSONObject(a);
                    String pcbaDeviceParamKey1 = jo.getString("pcbaDeviceParamKey");
                    String pcbaDeviceParamValue1 = jo.getString("pcbaDeviceParamValue");

                    List<String> oldKeys = new ArrayList<>();
                    for (PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam : oldPcbaDeviceRelatedDeviceParamList) {
                        oldKeys.add(pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamKey());
                    }
                    if(!oldKeys.contains(pcbaDeviceParamKey1)){
                        PcbaDeviceParam pcbaDeviceParam = pcbaDeviceParamDao.getPcbaDeviceParamByKey(pcbaDeviceParamKey1);
                        JSONObject j = new JSONObject();
                        j.put("key", pcbaDeviceParamKey1);
                        j.put("label", pcbaDeviceParam != null ? pcbaDeviceParam.getPcbaDeviceParamNameCn() : "");
                        j.put("oldValue", "");
                        j.put("newValue", pcbaDeviceParamValue1);
                        changeList.add(j);
                    }else{
                        for (PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam : oldPcbaDeviceRelatedDeviceParamList) {
                            String pcbaDeviceParamKey2 = pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamKey();
                            String pcbaDeviceParamValue2 = pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValue();
                            if (pcbaDeviceParamKey1.equals(pcbaDeviceParamKey2) && !pcbaDeviceParamValue1.equals(pcbaDeviceParamValue2)) {

                                PcbaDeviceParam pcbaDeviceParam = pcbaDeviceParamDao.getPcbaDeviceParamByKey(pcbaDeviceParamKey1);

                                JSONObject j = new JSONObject();
                                j.put("key", pcbaDeviceParamKey1);
                                j.put("label", pcbaDeviceParam != null ? pcbaDeviceParam.getPcbaDeviceParamNameCn() : "");
                                j.put("oldValue", pcbaDeviceParamValue2);
                                j.put("newValue", pcbaDeviceParamValue1);
                                changeList.add(j);
                            }
                        }
                    }
                }


                PcbaDeviceResource pcbaDeviceResource = new PcbaDeviceResource();
                pcbaDeviceResource.setBrandId(brandId);
                pcbaDeviceResource.setBrandTypeId(brandTypeId);
                pcbaDeviceResource.setStatus(Integer.parseInt(jsonObject.getString("status")));
                pcbaDeviceResource.setSort(Integer.parseInt(jsonObject.getString("sort")));
                pcbaDeviceResource.setNotes(notes);
                pcbaDeviceResource.setPcbaDevicePicture(jsonObject.getString("pcbaDevicePicture"));
                pcbaDeviceResource.setPicLength(jsonObject.get("picLength") != null && !"".equals(jsonObject.get("picLength").toString()) ? Integer.parseInt(jsonObject.getString("picLength")) : 0);
                pcbaDeviceResource.setPicWidth(jsonObject.get("picWidth") != null && !"".equals(jsonObject.get("picWidth").toString()) ? Integer.parseInt(jsonObject.getString("picWidth")) : 0);
                pcbaDeviceResource.setArchivesLink(jsonObject.getString("archivesLink"));
                pcbaDeviceResource.setPcbaDeviceTypeId(pcbaDeviceTypeId);
                pcbaDeviceResource.setUpdateTime(d);
                pcbaDeviceResource.setPcbaDeviceResourceId(pcbaDeviceResourceId);
                pcbaDeviceResource.setIsFilledBaseParams(1);

                // 认证通过状态
                Boolean isToAudit = false;
                if (oldPcbaDeviceResource.getAuditStatusBase() != null && oldPcbaDeviceResource.getAuditStatusBase() == 1) {
                    if (changeList.size() > 0) {
                        // 变成 待审核
                        //pcbaDeviceResource.setAuditStatusBase(jsonObject.get("auditStatusBase") != null && !"".equals(jsonObject.get("auditStatusBase").toString()) ? Integer.parseInt(jsonObject.getString("auditStatusBase")) : null);
                        pcbaDeviceResource.setAuditStatusBase(3);
                        pcbaDeviceResource.setSubmitterBase(Integer.parseInt(userId));
                        isToAudit = true;

                        // 添加 auditRecord 状态追踪
//                        AuditRecord addAuditRecord = new AuditRecord(
//                                 1,  pcbaDeviceResourceId,  3,  Integer.parseInt(userId),  JSON.toJSONString(changeList),  null,  new Date(),  null,  new Date()
//                        );
//                        auditRecordDao.addAuditRecord(addAuditRecord);
                    }
                    // 否则无需修改状态
                } else {
                    // 非认证通过状态，都需要变成 待审核
                    //pcbaDeviceResource.setAuditStatusBase(jsonObject.get("auditStatusBase") != null && !"".equals(jsonObject.get("auditStatusBase").toString()) ? Integer.parseInt(jsonObject.getString("auditStatusBase")) : null);
                    pcbaDeviceResource.setAuditStatusBase(3);
                    pcbaDeviceResource.setSubmitterBase(Integer.parseInt(userId));
                    isToAudit = true;

                    // 添加 auditRecord 状态追踪
//                    AuditRecord addAuditRecord = new AuditRecord(
//                            1,  pcbaDeviceResourceId,  3,  Integer.parseInt(userId),  JSON.toJSONString(changeList),  null,  new Date(),  null,  new Date()
//                    );
//                    auditRecordDao.addAuditRecord(addAuditRecord);
                }
                pcbaDeviceResourceDao.updatePcbaDeviceResource(pcbaDeviceResource);

                //2、如果新状态被修改为`审核中`，则会触发以下联动
                //   1）当前设备资源的工艺资源池认证状态变动，原先为`审核通过`的改为`审核中`，其他情况不用变【功能已完成】
                //   2）当前设备资源对应的设备工艺实际能力认证状态变动，原先为`审核通过`的改为`待提交审核`，其他情况不用变【功能已完成】
                //   3）使用到该设备资源的线体的基线审核状态不变；工艺审核状态原先为`审核通过`的改为`待提交审核`，其他情况不用变【功能已完成】
                /*if(isToAudit){
                    List<Integer> pLineIdList = new ArrayList<>();
                    //1)
                    if(oldPcbaDeviceResource.getAuditStatusTech() != null && oldPcbaDeviceResource.getAuditStatusTech() == 1){
                        pcbaDeviceResourceDao.updateAuditStatusTechWithSubmitter(pcbaDeviceResourceId, 3, Integer.parseInt(userId));
                    }
                    //2)
                    List<PcbaDevice> pdList = pcbaDeviceDao.getPcbaDeviceResourceByPcbaDeviceResourceId(pcbaDeviceResourceId);
                    for (PcbaDevice pcbaDevice : pdList) {
                        if(pcbaDevice.getParamsStatus() != null && pcbaDevice.getParamsStatus() == 1){
                            pcbaDeviceDao.updatePcbaDeviceParamsStatus(pcbaDevice.getPcbaDeviceId(), 4);
                        }

                        // 构造应用到此设备的线体
                        Integer pcbaLineId = pcbaDevice.getPcbaLineId();
                        if(!pLineIdList.contains(pcbaLineId)){
                            pLineIdList.add(pcbaLineId);
                        }
                    }
                    //3)
                    for (Integer plId : pLineIdList) {
                        PcbaLine oldPLine = pcbaLineDao.getPcbaLineById(plId);
                        *//*if(oldPLine != null && oldPLine.getParamsStatusBase() != null && oldPLine.getParamsStatusBase() == 1){
                            pcbaLineDao.auditPcbaLineParamBase(plId, 3, "");
                        }*//*
                        if(oldPLine != null && oldPLine.getParamsStatusActual() != null && oldPLine.getParamsStatusActual() == 1){
                            pcbaLineDao.auditPcbaLineParamTechActual(plId, 4, "");
                        }
                    }
                }*/

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldPcbaDeviceResource), JSONObject.toJSONString(pcbaDeviceResource)));

                /*//根据deviceId删除关联
                pcbaDeviceRelatedDeviceParamDao.deleteDeviceRelatedParam(pcbaDeviceResourceId);
                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 2, 1, new Date(), JSONObject.toJSONString(oldPcbaDeviceRelatedDeviceParamList), null));
                List<PcbaDeviceRelatedDeviceParam> list = new ArrayList<>();
                // 新增pcbaDeviceRelatedDeviceParam
                for(int a = 0;a<jsonArray.size();a++){
                    JSONObject jo = (JSONObject)jsonArray.get(a);
                    PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam = new PcbaDeviceRelatedDeviceParam();
                    pcbaDeviceRelatedDeviceParam.setCreateTime(d);
                    // 获取上面自增的id
                    pcbaDeviceRelatedDeviceParam.setPcbaDeviceResourceId(pcbaDeviceResource.getPcbaDeviceResourceId());
                    pcbaDeviceRelatedDeviceParam.setCreateTime(d);
                    pcbaDeviceRelatedDeviceParam.setPcbaDeviceParamKey(jo.getString("pcbaDeviceParamKey"));
                    pcbaDeviceRelatedDeviceParam.setPcbaDeviceTypeId(Integer.parseInt(jsonObject.getString("pcbaDeviceTypeId")));
                    pcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValue(jo.getString("pcbaDeviceParamValue"));
                    pcbaDeviceRelatedDeviceParamDao.addDeviceRelatedParam(pcbaDeviceRelatedDeviceParam);
                    list.add(pcbaDeviceRelatedDeviceParam);
                }*/
                // 原先删除 再新增的逻辑需要修改为 增量更新
                List<PcbaDeviceRelatedDeviceParam> list = new ArrayList<>();
                for (int a = 0; a < jsonArray.size(); a++) {
                    JSONObject jo = jsonArray.getJSONObject(a);
                    String k = jo.getString("pcbaDeviceParamKey");
                    Integer rsId = pcbaDeviceResource.getPcbaDeviceResourceId();
                    Integer pdId = Integer.parseInt(jsonObject.getString("pcbaDeviceTypeId"));
                    String v = jo.getString("pcbaDeviceParamValue");
                    // 判断是否存在
                    PcbaDeviceRelatedDeviceParam p = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(k, rsId);
                    if (p == null) {
                        // add
                        PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam = new PcbaDeviceRelatedDeviceParam();
                        pcbaDeviceRelatedDeviceParam.setCreateTime(d);
                        // 获取上面自增的id
                        pcbaDeviceRelatedDeviceParam.setPcbaDeviceResourceId(rsId);
                        pcbaDeviceRelatedDeviceParam.setCreateTime(d);
                        pcbaDeviceRelatedDeviceParam.setPcbaDeviceParamKey(k);
                        pcbaDeviceRelatedDeviceParam.setPcbaDeviceTypeId(pdId);
                        pcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValueAudit("");
                        pcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValue(v);
                        pcbaDeviceRelatedDeviceParamDao.addDeviceRelatedParam(pcbaDeviceRelatedDeviceParam);
                        list.add(pcbaDeviceRelatedDeviceParam);
                    } else {
                        // update
                        p.setCreateTime(d);
                        // 获取上面自增的id
                        p.setPcbaDeviceResourceId(rsId);
                        p.setCreateTime(d);
                        p.setPcbaDeviceParamKey(k);
                        p.setPcbaDeviceTypeId(pdId);
                        p.setPcbaDeviceParamValueAudit(p.getPcbaDeviceParamValue());
                        p.setPcbaDeviceParamValue(v);
                        pcbaDeviceRelatedDeviceParamDao.updateDeviceRelatedParam(p);
                        list.add(p);
                    }
                }

                // 级联触发 线体的最终状态
                coreAlgorithmService.cascadeUpdateLineFinalStatus(1, pcbaDeviceResourceId, null, null);

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(list)));
                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "mode 参数错误", "Error Param mode", null);
        } catch (Exception e) {
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    //@Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result addOrUpdateTechAndParamRelated(String data) {
        try {

            String userId = UserHeaderHolder.getUserId();

            JSONObject jsonObject = JSONObject.parseObject(data);
            String mode = jsonObject.getString("mode");
            JSONArray jsonArray = jsonObject.getJSONArray("pcbaDeviceRelatedTechParamList");
            Date d = new Date();
            if ("add".equals(mode)) {
                // 新增pcbaDevice
                // 设备类型 + 品牌 + 型号 + 备注  确定唯一性
                Integer pcbaDeviceTypeId = Integer.parseInt(jsonObject.get("pcbaDeviceTypeId").toString());

                // 判断 is_tech_own = 1,该设备类型是否已添加【此类有且仅能添加一个】
                PcbaDeviceResource p = pcbaDeviceResourceDao.getByConditionsJudgeUnique(pcbaDeviceTypeId, null, null, null, null);
                if (p != null) {
                    return ResultUtil.error(500, "当前已存在该工艺，无法重复添加", "Already Exist", null);
                }

                Integer brandId = jsonObject.get("brand") != null && !"".equals(jsonObject.get("brand").toString()) ? Integer.parseInt(jsonObject.get("brand").toString()) : null;
                Integer brandTypeId = jsonObject.get("type") != null && !"".equals(jsonObject.get("type").toString()) ? Integer.parseInt(jsonObject.get("type").toString()) : null;
                Integer status = jsonObject.get("status") != null && !"".equals(jsonObject.get("status").toString()) ? Integer.parseInt(jsonObject.get("status").toString()) : null;
                Integer sort = jsonObject.get("sort") != null && !"".equals(jsonObject.get("sort").toString()) ? Integer.parseInt(jsonObject.get("sort").toString()) : null;
                String notes = jsonObject.get("notes") != null && !"".equals(jsonObject.get("notes")) ? jsonObject.get("notes").toString() : null;
                String pcbaDevicePicture = jsonObject.get("pcbaDevicePicture") != null && !"".equals(jsonObject.get("pcbaDevicePicture")) ? jsonObject.get("pcbaDevicePicture").toString() : null;
                String archivesLink = jsonObject.get("archivesLink") != null && !"".equals(jsonObject.get("archivesLink")) ? jsonObject.get("archivesLink").toString() : null;

                PcbaDeviceResource judgeUniquePcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsJudgeUnique(pcbaDeviceTypeId, brandId, brandTypeId, notes, null);
                if (judgeUniquePcbaDeviceResource != null) {
                    return ResultUtil.error(500, "当前已存在相同的 设备类型 + 品牌 + 型号 + 备注 ", "Already Exist Same Kind", null);
                }

                PcbaDeviceType pcbaDeviceType = pcbaDeviceTypeDao.getById(pcbaDeviceTypeId);
                Integer isTechOwn = pcbaDeviceType.getIsTechOwn();

                PcbaDeviceResource pcbaDeviceResource = new PcbaDeviceResource();
                pcbaDeviceResource.setBrandId(brandId);
                pcbaDeviceResource.setBrandTypeId(brandTypeId);
                pcbaDeviceResource.setStatus(status);
                pcbaDeviceResource.setSort(sort);
                pcbaDeviceResource.setNotes(notes);
                pcbaDeviceResource.setPcbaDevicePicture(pcbaDevicePicture);
                pcbaDeviceResource.setArchivesLink(archivesLink);
                pcbaDeviceResource.setPcbaDeviceTypeId(pcbaDeviceTypeId);
                pcbaDeviceResource.setCreateTime(d);
                pcbaDeviceResource.setIsFilledTechParams(1);
                pcbaDeviceResource.setSubmitterTech(Integer.parseInt(userId));
                if(isTechOwn != null && isTechOwn == 1){
                    pcbaDeviceResource.setAuditStatusTech(1);
                    pcbaDeviceResource.setAuditStatusBase(1);
                }else{
                    pcbaDeviceResource.setAuditStatusTech(jsonObject.get("auditStatusTech") != null && !"".equals(jsonObject.get("auditStatusTech").toString()) ? Integer.parseInt(jsonObject.getString("auditStatusTech")) : null);
                    pcbaDeviceResource.setAuditStatusBase(4);
                }
                pcbaDeviceResourceDao.addPcbaDeviceResource(pcbaDeviceResource);

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(pcbaDeviceResource)));

                List<PcbaDeviceRelatedTechParam> list = new ArrayList<>();
                // 新增pcbaDeviceRelatedDeviceParam
                for (int a = 0; a < jsonArray.size(); a++) {
                    JSONObject jo = (JSONObject) jsonArray.get(a);
                    PcbaDeviceRelatedTechParam pcbaDeviceRelatedTechParam = new PcbaDeviceRelatedTechParam();
                    pcbaDeviceRelatedTechParam.setCreateTime(d);
                    // 获取上面自增的id
                    pcbaDeviceRelatedTechParam.setPcbaDeviceResourceId(pcbaDeviceResource.getPcbaDeviceResourceId());
                    pcbaDeviceRelatedTechParam.setCreateTime(d);
                    pcbaDeviceRelatedTechParam.setTechDeviceParamKey(jo.get("techDeviceParamKey").toString());
                    pcbaDeviceRelatedTechParam.setPcbaDeviceTypeId(Integer.parseInt(jo.get("pcbaDeviceTypeId").toString()));
                    pcbaDeviceRelatedTechParam.setTechDeviceParamValue(jo.get("techDeviceParamValue").toString());
                    pcbaDeviceRelatedTechParamDao.addDeviceRelatedParam(pcbaDeviceRelatedTechParam);
                    list.add(pcbaDeviceRelatedTechParam);
                }

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(list)));

                return ResultUtil.success(null);
            } else if ("update".equals(mode)) {
                Integer pcbaDeviceResourceId = jsonObject.getInteger("pcbaDeviceResourceId");
                if (pcbaDeviceResourceId == null || "".equals(pcbaDeviceResourceId.toString())) {
                    return ResultUtil.error(500, "缺少参数pcbaDeviceResourceId", "Miss Param pcbaDeviceResourceId", null);
                }

                Integer pcbaDeviceTypeId = Integer.parseInt(jsonObject.get("pcbaDeviceTypeId").toString());
                Integer brandId = jsonObject.get("brand") != null && !"".equals(jsonObject.get("brand").toString()) ? Integer.parseInt(jsonObject.get("brand").toString()) : null;
                Integer brandTypeId = jsonObject.get("type") != null && !"".equals(jsonObject.get("type").toString()) ? Integer.parseInt(jsonObject.get("type").toString()) : null;
                Integer status = jsonObject.get("status") != null && !"".equals(jsonObject.get("status").toString()) ? Integer.parseInt(jsonObject.get("status").toString()) : null;
                Integer sort = jsonObject.get("sort") != null && !"".equals(jsonObject.get("sort").toString()) ? Integer.parseInt(jsonObject.get("sort").toString()) : null;
                String notes = jsonObject.get("notes") != null && !"".equals(jsonObject.get("notes")) ? jsonObject.get("notes").toString() : null;
                String pcbaDevicePicture = jsonObject.get("pcbaDevicePicture") != null && !"".equals(jsonObject.get("pcbaDevicePicture")) ? jsonObject.get("pcbaDevicePicture").toString() : null;
                String archivesLink = jsonObject.get("archivesLink") != null && !"".equals(jsonObject.get("archivesLink")) ? jsonObject.get("archivesLink").toString() : null;

                PcbaDeviceResource judgeUniquePcbaDeviceResource;
                if (notes == null || "".equals(notes)) {
                    judgeUniquePcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsWithoutNotes(pcbaDeviceTypeId, brandId, brandTypeId, pcbaDeviceResourceId);
                } else {
                    judgeUniquePcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsJudgeUnique(pcbaDeviceTypeId, brandId, brandTypeId, notes, pcbaDeviceResourceId);
                }
                if (judgeUniquePcbaDeviceResource != null) {
                    return ResultUtil.error(500, "当前已存在相同的 设备类型 + 品牌 + 型号 + 备注 ", "Already Exist Same Kind", null);
                }

                PcbaDeviceResource oldPcbaDeviceResource = pcbaDeviceResourceDao.getById(pcbaDeviceResourceId);

                // 获取原先的 工艺参数
                List<PcbaDeviceRelatedTechParam> oldPcbaDeviceRelatedTechParamList = pcbaDeviceRelatedTechParamDao.getAllByDeviceResourceId(pcbaDeviceResourceId);

                Boolean isChangeParams = false;
                // 先判断池子key是否都存在
                List<String> oldKeyList = new ArrayList<>();
                for (PcbaDeviceRelatedTechParam pcbaDeviceRelatedTechParam : oldPcbaDeviceRelatedTechParamList) {
                    String pcbaDeviceParamKey2 = pcbaDeviceRelatedTechParam.getTechDeviceParamKey();
                    oldKeyList.add(pcbaDeviceParamKey2);
                }
                for (int a = 0; a < jsonArray.size(); a++) {
                    JSONObject jo = (JSONObject) jsonArray.get(a);
                    String techDeviceParamKey1 = jo.getString("techDeviceParamKey");
                    if (!oldKeyList.toString().contains(techDeviceParamKey1)) {
                        isChangeParams = true;
                        break;
                    }
                }
                for (int a = 0; a < jsonArray.size(); a++) {
                    JSONObject jo = (JSONObject) jsonArray.get(a);
                    String techDeviceParamKey1 = jo.getString("techDeviceParamKey");
                    String techDeviceParamValue1 = jo.getString("techDeviceParamValue");
                    for (PcbaDeviceRelatedTechParam pcbaDeviceRelatedTechParam : oldPcbaDeviceRelatedTechParamList) {
                        String techDeviceParamKey2 = pcbaDeviceRelatedTechParam.getTechDeviceParamKey();
                        String techDeviceParamValue2 = pcbaDeviceRelatedTechParam.getTechDeviceParamValue();
                        if (techDeviceParamKey1.equals(techDeviceParamKey2) && !techDeviceParamValue1.equals(techDeviceParamValue2)) {
                            isChangeParams = true;
                            break;
                        }
                    }
                }

                PcbaDeviceResource pcbaDeviceResource = new PcbaDeviceResource();
                pcbaDeviceResource.setBrandId(brandId);
                pcbaDeviceResource.setBrandTypeId(brandTypeId);
                pcbaDeviceResource.setStatus(status);
                pcbaDeviceResource.setSort(sort);
                pcbaDeviceResource.setNotes(notes);
                pcbaDeviceResource.setPcbaDevicePicture(pcbaDevicePicture);
                pcbaDeviceResource.setArchivesLink(archivesLink);
                pcbaDeviceResource.setPcbaDeviceTypeId(pcbaDeviceTypeId);
                pcbaDeviceResource.setUpdateTime(d);
                pcbaDeviceResource.setPcbaDeviceResourceId(pcbaDeviceResourceId);
                pcbaDeviceResource.setIsFilledTechParams(1);
                // 认证通过状态
                Boolean isToAudit = false;
                if (oldPcbaDeviceResource.getAuditStatusTech() != null && oldPcbaDeviceResource.getAuditStatusTech() == 1) {
                    if (isChangeParams) {
                        // 变成 待审核
                        //pcbaDeviceResource.setAuditStatusTech(jsonObject.get("auditStatusTech") != null && !"".equals(jsonObject.get("auditStatusTech").toString()) ? Integer.parseInt(jsonObject.getString("auditStatusTech")) : null);
                        pcbaDeviceResource.setAuditStatusTech(3);
                        pcbaDeviceResource.setSubmitterTech(Integer.parseInt(userId));
                        isToAudit = true;
                    }
                    // 否则无需修改状态
                } else {
                    // 非认证通过状态，都需要变成 待审核
                    //pcbaDeviceResource.setAuditStatusTech(jsonObject.get("auditStatusTech") != null && !"".equals(jsonObject.get("auditStatusTech").toString()) ? Integer.parseInt(jsonObject.getString("auditStatusTech")) : null);
                    pcbaDeviceResource.setAuditStatusTech(3);
                    pcbaDeviceResource.setSubmitterTech(Integer.parseInt(userId));
                    isToAudit = true;
                }
                pcbaDeviceResourceDao.updatePcbaDeviceResource(pcbaDeviceResource);

                /*//2、如果新状态被修改为`审核中`，则会触发以下联动
                //   1）当前设备资源对应的设备工艺实际能力认证状态变动，原先为`审核通过`的改为`待提交审核`，其他情况不用变【功能已完成】
                //   2）使用到该设备资源的线体的工艺整线实际能力审核状态均变动，原先为`审核通过`的改为`待提交审核`，其他情况不用变【功能已完成】
                if(isToAudit){
                    List<Integer> pLineIdList = new ArrayList<>();
                    List<PcbaDevice> pdList = pcbaDeviceDao.getPcbaDeviceResourceByPcbaDeviceResourceId(pcbaDeviceResourceId);
                    //1)
                    for (PcbaDevice pcbaDevice : pdList) {
                        if(pcbaDevice.getParamsStatus() != null && pcbaDevice.getParamsStatus() == 1){
                            pcbaDeviceDao.updatePcbaDeviceParamsStatus(pcbaDevice.getPcbaDeviceId(), 4);
                        }

                        // 构造应用到此设备的线体
                        Integer pcbaLineId = pcbaDevice.getPcbaLineId();
                        if(!pLineIdList.contains(pcbaLineId)){
                            pLineIdList.add(pcbaLineId);
                        }
                    }
                    //2)
                    for (Integer plId : pLineIdList) {
                        PcbaLine oldPLine = pcbaLineDao.getPcbaLineById(plId);
                        if(oldPLine != null && oldPLine.getParamsStatusActual() != null && oldPLine.getParamsStatusActual() == 1){
                            pcbaLineDao.auditPcbaLineParamTechActual(plId, 4, "");
                        }
                    }
                }*/

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldPcbaDeviceResource), JSONObject.toJSONString(pcbaDeviceResource)));

                List<PcbaDeviceRelatedTechParam> pcbaDeviceRelatedTechParamList = pcbaDeviceRelatedTechParamDao.getAllByDeviceResourceId(pcbaDeviceResourceId);
                /*//根据deviceId删除关联
                pcbaDeviceRelatedTechParamDao.deleteDeviceRelatedParam(pcbaDeviceResourceId);
                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 2, 1, new Date(), JSONObject.toJSONString(pcbaDeviceRelatedTechParamList), null));
                List<PcbaDeviceRelatedTechParam> list = new ArrayList<>();
                // 新增pcbaDeviceRelatedDeviceParam
                for(int a = 0;a<jsonArray.size();a++){
                    JSONObject jo = (JSONObject)jsonArray.get(a);
                    PcbaDeviceRelatedTechParam pcbaDeviceRelatedTechParam = new PcbaDeviceRelatedTechParam();
                    pcbaDeviceRelatedTechParam.setCreateTime(d);
                    // 获取上面自增的id
                    pcbaDeviceRelatedTechParam.setPcbaDeviceResourceId(pcbaDeviceResource.getPcbaDeviceResourceId());
                    pcbaDeviceRelatedTechParam.setCreateTime(d);
                    pcbaDeviceRelatedTechParam.setTechDeviceParamKey(jo.get("techDeviceParamKey").toString());
                    pcbaDeviceRelatedTechParam.setPcbaDeviceTypeId(Integer.parseInt(jsonObject.get("pcbaDeviceTypeId").toString()));
                    pcbaDeviceRelatedTechParam.setTechDeviceParamValue(jo.get("techDeviceParamValue").toString());
                    pcbaDeviceRelatedTechParamDao.addDeviceRelatedParam(pcbaDeviceRelatedTechParam);
                    list.add(pcbaDeviceRelatedTechParam);
                }*/
                // 原先删除 再新增的逻辑需要修改为 增量更新
                List<PcbaDeviceRelatedTechParam> list = new ArrayList<>();
                for (int a = 0; a < jsonArray.size(); a++) {
                    JSONObject jo = jsonArray.getJSONObject(a);
                    String k = jo.getString("techDeviceParamKey");
                    Integer rsId = pcbaDeviceResource.getPcbaDeviceResourceId();
                    Integer pdId = Integer.parseInt(jsonObject.getString("pcbaDeviceTypeId"));
                    String v = jo.getString("techDeviceParamValue");
                    // 判断是否存在
                    PcbaDeviceRelatedTechParam p = pcbaDeviceRelatedTechParamDao.getPcbaDeviceRelatedTechParamByKeyAndDeviceResourceId(k, rsId);
                    if (p == null) {
                        // add
                        PcbaDeviceRelatedTechParam pcbaDeviceRelatedTechParam = new PcbaDeviceRelatedTechParam();
                        pcbaDeviceRelatedTechParam.setCreateTime(d);
                        // 获取上面自增的id
                        pcbaDeviceRelatedTechParam.setPcbaDeviceResourceId(rsId);
                        pcbaDeviceRelatedTechParam.setCreateTime(d);
                        pcbaDeviceRelatedTechParam.setTechDeviceParamKey(k);
                        pcbaDeviceRelatedTechParam.setPcbaDeviceTypeId(pdId);
                        pcbaDeviceRelatedTechParam.setTechDeviceParamValueAudit("");
                        pcbaDeviceRelatedTechParam.setTechDeviceParamValue(v);
                        pcbaDeviceRelatedTechParamDao.addDeviceRelatedParam(pcbaDeviceRelatedTechParam);
                        list.add(pcbaDeviceRelatedTechParam);
                    } else {
                        // update
                        p.setCreateTime(d);
                        // 获取上面自增的id
                        p.setPcbaDeviceResourceId(rsId);
                        p.setCreateTime(d);
                        p.setTechDeviceParamKey(k);
                        p.setPcbaDeviceTypeId(pdId);
                        if (p.getTechDeviceParamValueAudit() == null || "".equals(p.getTechDeviceParamValueAudit())) {
                            p.setTechDeviceParamValueAudit(p.getTechDeviceParamValue());
                        }
                        p.setTechDeviceParamValue(v);
                        pcbaDeviceRelatedTechParamDao.updateDeviceRelatedParam(p);
                        list.add(p);
                    }
                }

                // 级联触发 线体的最终状态
                coreAlgorithmService.cascadeUpdateLineFinalStatus(1, pcbaDeviceResourceId, null, null);

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(list)));

                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "mode 参数错误", "Error Param mode", null);
        } catch (Exception e) {
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result judgeUnique(Integer pcbaDeviceTypeId, Integer brandId, Integer brandTypeId, String notes, Integer pcbaDeviceResourceId) {
        try {
            PcbaDeviceResource judgeUniquePcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsJudgeUnique(pcbaDeviceTypeId, brandId, brandTypeId, notes, pcbaDeviceResourceId);
            if (judgeUniquePcbaDeviceResource != null) {
                return ResultUtil.error(500, "当前已存在相同的 设备类型 + 品牌 + 型号 + 备注 ", "Already Exist Same Kind", null);
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result judgeUniqueByDeviceTypeAndBrandAndBrandType(Integer pcbaDeviceTypeId, Integer brandId, Integer brandTypeId, Integer pcbaDeviceResourceId) {
        try {
            PcbaDeviceResource judgeUniquePcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsJudgeUnique(pcbaDeviceTypeId, brandId, brandTypeId, null, pcbaDeviceResourceId);
            if (judgeUniquePcbaDeviceResource != null) {
                Integer resourceId = judgeUniquePcbaDeviceResource.getPcbaDeviceResourceId();
                List<PcbaDeviceRelatedDeviceParam> pcbaDeviceRelatedDeviceParamList = pcbaDeviceRelatedDeviceParamDao.getAllByDeviceResourceId(resourceId);

                // 返回对应设备资源的参数值
                return ResultUtil.error(501, "当前已存在相同的 设备类型 + 品牌 + 型号，已自动加载对应设备参数, 提交需要添加备注以区分 ", "Already Exist Same Kind", pcbaDeviceRelatedDeviceParamList);
            }
            // 返回该设备类型的参数池
            List<PcbaDeviceParam> allPcbaDeviceParam = pcbaDeviceParamDao.getAllPcbaDeviceParam(pcbaDeviceTypeId, null, null);
            return ResultUtil.success(allPcbaDeviceParam);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result exportDeviceResourceAndPcbaDeviceParamTable(String data) {
        try {
            List<PcbaDeviceResource> list = new ArrayList<>();
            if (data == null || "".equals(data)) {
                return ResultUtil.error(500, "缺少参数data", "Miss Param data", null);
            }
            JSONObject jsonObject = JSONObject.parseObject(data);
            String type = jsonObject.getString("type");
            if ("1".equals(type)) {
                // 按条件导出
                String deviceType2 = jsonObject.getString("deviceType2");
                String chooseBrandAndType2 = jsonObject.getString("chooseBrandAndType2");
                //JSONArray jsonArray1 = JSONArray.parseArray(deviceType2);
                JSONArray jsonArray2 = JSONArray.parseArray(chooseBrandAndType2);
                //for (Object o1 : jsonArray1) {
                //Integer deviceTypeId = (Integer)o1;
                if (jsonArray2.size() > 0) {
                    for (Object o2 : jsonArray2) {
                        JSONArray jsonArray3 = (JSONArray) o2;
                        Integer pcbaDeviceTypeId = (Integer) jsonArray3.get(0);
                        Integer brandId = (Integer) jsonArray3.get(1);
                        Integer brandTypeId = (Integer) jsonArray3.get(2);

                        PcbaDeviceResource pcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsJudgeUnique(pcbaDeviceTypeId, brandId, brandTypeId, null, null);
                        if (pcbaDeviceResource != null) {
                            if (!list.contains(pcbaDeviceResource)) {
                                list.add(pcbaDeviceResource);
                            }
                        }
                    }
                }/*else{
                        List<PcbaDeviceResource> pcbaDeviceResource = pcbaDeviceResourceDao.getByConditions(deviceTypeId, null, null, null, null);
                        if(pcbaDeviceResource != null){
                            list.addAll(pcbaDeviceResource);
                        }
                    }*/
                //}
            } else if ("2".equals(type)) {
                // 导出全部
                list = pcbaDeviceResourceDao.getAllPcbaDeviceResource();
            } else if ("3".equals(type)) {
                // 导出选中
                JSONArray jsonArray = jsonObject.getJSONArray("list");
                for (int a = 0; a < jsonArray.size(); a++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(a);
                    String pcbaDeviceResourceId = jsonObject1.getString("pcbaDeviceResourceId");
                    PcbaDeviceResource pcbaDeviceResource = pcbaDeviceResourceDao.getById(Integer.parseInt(pcbaDeviceResourceId));
                    list.add(pcbaDeviceResource);
                }
            } else {
                return ResultUtil.error(500, "错误参数type", "Error Param type", null);
            }
            // 拿到list查询基线参数
            for (PcbaDeviceResource pcbaDeviceResource : list) {
                Integer pcbaDeviceResourceId = pcbaDeviceResource.getPcbaDeviceResourceId();
                Integer pcbaDeviceTypeId = pcbaDeviceResource.getPcbaDeviceTypeId();
                pcbaDeviceResource.setBrand(brandDao.getBrandById(pcbaDeviceResource.getBrandId()));
                pcbaDeviceResource.setBrandType(brandTypeDao.getBrandTypeByIdAndBrand(pcbaDeviceResource.getBrandTypeId(), pcbaDeviceResource.getBrandId()));
                PcbaDeviceType pcbaDeviceType = pcbaDeviceTypeDao.getById(pcbaDeviceTypeId);
                List<PcbaDeviceParamType> pcbaDeviceParamTypeList = pcbaDeviceParamTypeDao.getPcbaDeviceParamTypeByPcbaDeviceTypeId(pcbaDeviceTypeId, null);
                for (PcbaDeviceParamType pcbaDeviceParamType : pcbaDeviceParamTypeList) {
                    Integer pcbaDeviceParamTypeId = pcbaDeviceParamType.getPcbaDeviceParamTypeId();
                    List<PcbaDeviceParam> pcbaDeviceParamList = pcbaDeviceParamDao.getAllPcbaDeviceParam(pcbaDeviceTypeId, pcbaDeviceParamTypeId, null);
                    for (PcbaDeviceParam pcbaDeviceParam : pcbaDeviceParamList) {
                        String pcbaDeviceParamKey = pcbaDeviceParam.getPcbaDeviceParamKey();
                        PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(pcbaDeviceParamKey, pcbaDeviceResourceId);
                        if (pcbaDeviceRelatedDeviceParam != null) {
                            pcbaDeviceParam.setPcbaDeviceParamValue(pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValue());
                        }
                    }
                    pcbaDeviceParamType.setPcbaDeviceParamList(pcbaDeviceParamList);
                }
                pcbaDeviceType.setPcbaDeviceParamTypeList(pcbaDeviceParamTypeList);
                pcbaDeviceResource.setPcbaDeviceType(pcbaDeviceType);
            }

            if (list.size() == 0) {
                return ResultUtil.error(500, "待导出数据为空", "Empty Data", null);
            }

            // 处理渲染excel
            String excelName = "设备基线资源池";
            // 创建工作簿对象
            Workbook workbook = new XSSFWorkbook();
            for (PcbaDeviceResource pcbaDeviceResource : list) {
                String pcbaDeviceTypeNameCn = pcbaDeviceResource.getPcbaDeviceType().getPcbaDeviceTypeNameCn();
                String brandName = pcbaDeviceResource.getBrand().getBrandName();
                String brandTypeName = pcbaDeviceResource.getBrandType() != null ? pcbaDeviceResource.getBrandType().getBrandTypeName() : "";
                String notes = pcbaDeviceResource.getNotes();
                String sheetName = pcbaDeviceTypeNameCn + "-" + brandName + "-" + brandTypeName + '-' + notes;
                // 创建工作表对象
                Sheet sheet = workbook.createSheet(CommonUtils.handleSheetName(sheetName));
                // 创建行和单元格对象
                Row row = sheet.createRow(0);

                CellStyle bigTitleContextCellStyle = workbook.createCellStyle();
                Font bigTitleFont = workbook.createFont();
                bigTitleFont.setBold(true);
                bigTitleFont.setFontHeightInPoints((short) 20);
                bigTitleContextCellStyle.setFont(bigTitleFont);
                bigTitleContextCellStyle.setAlignment(HorizontalAlignment.CENTER);
                bigTitleContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

                // 第一行大标题【设备基线能力参数反馈表】
                Cell cell = row.createCell(0);
                cell.setCellValue(excelName);
                cell.setCellStyle(bigTitleContextCellStyle);
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
                // 第二行 【注：模板内容不涉及，则填写NA】
                row = sheet.createRow(1);
                cell = row.createCell(0);
                cell.setCellValue("注：模板内容不涉及，则填写NA");
                sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 7));


                CellStyle bodyContextCellStyle = workbook.createCellStyle();
                DataFormat format = workbook.createDataFormat();
                bodyContextCellStyle.setDataFormat(format.getFormat("@"));
                bodyContextCellStyle.setBorderBottom(BorderStyle.THIN);
                bodyContextCellStyle.setBorderLeft(BorderStyle.THIN);
                bodyContextCellStyle.setBorderRight(BorderStyle.THIN);
                bodyContextCellStyle.setBorderTop(BorderStyle.THIN);
                bodyContextCellStyle.setAlignment(HorizontalAlignment.LEFT);
                bodyContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

                CellStyle titleContextCellStyle = workbook.createCellStyle();
                titleContextCellStyle.setBorderBottom(BorderStyle.THIN);
                titleContextCellStyle.setBorderLeft(BorderStyle.THIN);
                titleContextCellStyle.setBorderRight(BorderStyle.THIN);
                titleContextCellStyle.setBorderTop(BorderStyle.THIN);
                titleContextCellStyle.setAlignment(HorizontalAlignment.CENTER);
                titleContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                // 设置背景色为红色
                titleContextCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
                // 创建字体对象
                Font titleFont = workbook.createFont();
                // 设置字体颜色为蓝色
                titleFont.setColor(IndexedColors.WHITE.getIndex());
                titleFont.setBold(true);
                titleContextCellStyle.setFont(titleFont);
                // 设置填充类型为填充实体背景
                titleContextCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                List<Map<String, Object>> titleList = new ArrayList<>();

                Map<String, Object> map = new HashMap<>();
                map = new HashMap<>();
                map.put("title", "设备");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "品牌");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "型号");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "备注");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "项目大类");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "设备能力评估项");
                map.put("width", 15000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "设备加工能力参数");
                map.put("width", 10000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "设计说明");
                map.put("width", 15000);
                titleList.add(map);
                row = sheet.createRow(2);
                for (int a = 0; a < titleList.size(); a++) {
                    sheet.setColumnWidth(a, Integer.parseInt(titleList.get(a).get("width").toString()));
                    sheet.setDefaultRowHeight((short) 450);
                    cell = row.createCell(a);
                    // 向单元格中写入数据
                    cell.setCellValue(titleList.get(a).get("title").toString());
                    cell.setCellStyle(titleContextCellStyle);
                }

                int index = 0; // 序号
                int beginIndex1 = 3; //用于计算合并单元格 【设备】一列，从第四行开始
                int beginIndex2 = 3; //用于计算合并单元格 【项目大类】一列，从第四行开始
                // 渲染数据
                List<PcbaDeviceParamType> pcbaDeviceParamTypeList = pcbaDeviceResource.getPcbaDeviceType().getPcbaDeviceParamTypeList();
                if (pcbaDeviceParamTypeList != null && pcbaDeviceParamTypeList.size() > 0) {
                    for (int c = 0; c < pcbaDeviceParamTypeList.size(); c++) {
                        List<PcbaDeviceParam> pcbaDeviceParamList = pcbaDeviceParamTypeList.get(c).getPcbaDeviceParamList();
                        if (pcbaDeviceParamList != null && pcbaDeviceParamList.size() > 0) {
                            for (int d = 0; d < pcbaDeviceParamList.size(); d++) {
                                index++;
                                Row row_ = sheet.createRow(index + 2);

                                // 序号
                                Cell cell_ = row_.createCell(0);
//                                cell_.setCellValue(index);
//                                cell_.setCellStyle(bodyContextCellStyle);

                                // 设备
                                cell_ = row_.createCell(0);
                                cell_.setCellValue(pcbaDeviceTypeNameCn);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 品牌
                                cell_ = row_.createCell(1);
                                cell_.setCellValue(brandName);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 型号
                                cell_ = row_.createCell(2);
                                cell_.setCellValue(brandTypeName);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 备注
                                cell_ = row_.createCell(3);
                                cell_.setCellValue(notes);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 项目大类
                                cell_ = row_.createCell(4);
                                cell_.setCellValue(pcbaDeviceParamTypeList.get(c).getPcbaDeviceParamTypeName());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 设备能力评估项
                                cell_ = row_.createCell(5);
                                cell_.setCellValue(pcbaDeviceParamList.get(d).getPcbaDeviceParamNameCn());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 设备加工参数
                                cell_ = row_.createCell(6);
                                cell_.setCellValue(pcbaDeviceParamList.get(d).getPcbaDeviceParamValue());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 设计说明
                                /*1：普通文本
                                2.下拉选择
                                3：文件上传
                                4:  下拉多选
                                10：数值类型[整数]
                                11：数值类型[小数]
                                21：百分比
                                31：不限制 or NA or 数字
                                */
                                cell_ = row_.createCell(7);
                                cell_.setCellValue(pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 1 ? "普通文本" :
                                        (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 2 ? "下拉选择" + "(" + pcbaDeviceParamList.get(d).getPcbaDeviceParamOptions() + ")" :
                                                (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 3 ? "文件上传" :
                                                        (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 4 ? "下拉多选" + "(" + pcbaDeviceParamList.get(d).getPcbaDeviceParamOptions() + ")" :
                                                                (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 11 ? "整数" :
                                                                        (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 12 ? "小数" :
                                                                                (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 21 ? "百分比" :
                                                                                        (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 31 ? "不限制 or NA or 数字" : ""))))))));
                                cell_.setCellStyle(bodyContextCellStyle);

                            }
                            // 合并第5列 【项目大类】
                            // System.out.println("pcbaDeviceParamList.size()=" + pcbaDeviceParamList.size());
                            if (pcbaDeviceParamList.size() > 1) {
                                if (index + 2 > beginIndex2) {
                                    sheet.addMergedRegion(new CellRangeAddress(beginIndex2, index + 2, 4, 4));
                                    beginIndex2 = index + 3;
                                }
                            } else {
                                beginIndex2 = index + 3;
                            }
                        }
                    }
                    // 合并第二列 【设备】第三列 第四列
                    //System.out.println("beginRow===" + beginIndex1);
                    //System.out.println("lastRow===" + (index + 2));
                    //if(pcbaDeviceParamTypeList.size() > 1){
                    if (index + 2 > beginIndex1) {
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 0, 0));
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 1, 1));
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 2, 2));
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 3, 3));
                        beginIndex1 = index + 3;
                    }
                    /*}else{
                        beginIndex2 = index + 3;
                    }*/
                }
            }
            String fileName = excelName + CommonUtils.getTimestamp() + ".xlsx";
            String pathPrefix = fileSaveUrl + "exportExcels\\";
            File folder = new File(pathPrefix);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String filePath = pathPrefix + fileName;
            // 导出Excel文件
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();

            byte[] bytedata = null;
            InputStream in = new FileInputStream(filePath);
            bytedata = new byte[in.available()];
            in.read(bytedata);
            in.close();
            java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
            String base64 = encoder.encodeToString(bytedata);

            Map<String, Object> resMap = new HashMap<>();
            resMap.put("list", list);
            resMap.put("base64", base64);
            resMap.put("fileName", fileName);
            return ResultUtil.success(resMap);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result exportDeviceResourceAndPcbaDeviceParamTableOfTemplates(String pcbaDeviceTypeIds) {
        try {
            if (pcbaDeviceTypeIds == null || "".equals(pcbaDeviceTypeIds)) {
                return ResultUtil.error(500, "缺少参数pcbaDeviceTypeIds", "Miss Param pcbaDeviceTypeIds", null);
            }
            String[] pcbaDeviceTypeIdArr = pcbaDeviceTypeIds.split(",");

            // 处理渲染excel
            String excelName = "设备基线资源池";
            // 创建工作簿对象
            Workbook workbook = new XSSFWorkbook();
            for (String s : pcbaDeviceTypeIdArr) {
                Integer pcbaDeviceTypeId = Integer.parseInt(s);
                String pcbaDeviceTypeNameCn = pcbaDeviceTypeDao.getById(pcbaDeviceTypeId).getPcbaDeviceTypeNameCn();
                String brandName = "";
                String brandTypeName = "";
                String notes = "";
                String sheetName = pcbaDeviceTypeNameCn;
                // 创建工作表对象
                Sheet sheet = workbook.createSheet(CommonUtils.handleSheetName(sheetName));
                // 创建行和单元格对象
                Row row = sheet.createRow(0);

                CellStyle bigTitleContextCellStyle = workbook.createCellStyle();
                Font bigTitleFont = workbook.createFont();
                bigTitleFont.setBold(true);
                bigTitleFont.setFontHeightInPoints((short) 20);
                bigTitleContextCellStyle.setFont(bigTitleFont);
                bigTitleContextCellStyle.setAlignment(HorizontalAlignment.CENTER);
                bigTitleContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

                // 第一行大标题【设备基线能力参数反馈表】
                Cell cell = row.createCell(0);
                cell.setCellValue(excelName);
                cell.setCellStyle(bigTitleContextCellStyle);
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
                // 第二行 【注：模板内容不涉及，则填写NA】
                row = sheet.createRow(1);
                cell = row.createCell(0);
                cell.setCellValue("注：模板内容不涉及，则填写NA");
                sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 7));


                CellStyle bodyContextCellStyle = workbook.createCellStyle();
                DataFormat format = workbook.createDataFormat();
                bodyContextCellStyle.setDataFormat(format.getFormat("@"));
                bodyContextCellStyle.setBorderBottom(BorderStyle.THIN);
                bodyContextCellStyle.setBorderLeft(BorderStyle.THIN);
                bodyContextCellStyle.setBorderRight(BorderStyle.THIN);
                bodyContextCellStyle.setBorderTop(BorderStyle.THIN);
                bodyContextCellStyle.setAlignment(HorizontalAlignment.LEFT);
                bodyContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

                CellStyle titleContextCellStyle = workbook.createCellStyle();
                titleContextCellStyle.setBorderBottom(BorderStyle.THIN);
                titleContextCellStyle.setBorderLeft(BorderStyle.THIN);
                titleContextCellStyle.setBorderRight(BorderStyle.THIN);
                titleContextCellStyle.setBorderTop(BorderStyle.THIN);
                titleContextCellStyle.setAlignment(HorizontalAlignment.CENTER);
                titleContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                // 设置背景色为红色
                titleContextCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
                // 创建字体对象
                Font titleFont = workbook.createFont();
                // 设置字体颜色为蓝色
                titleFont.setColor(IndexedColors.WHITE.getIndex());
                titleFont.setBold(true);
                titleContextCellStyle.setFont(titleFont);
                // 设置填充类型为填充实体背景
                titleContextCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                List<Map<String, Object>> titleList = new ArrayList<>();

                Map<String, Object> map = new HashMap<>();
                map = new HashMap<>();
                map.put("title", "设备");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "品牌");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "型号");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "备注");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "项目大类");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "设备能力评估项");
                map.put("width", 15000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "设备加工能力参数");
                map.put("width", 10000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "设计说明");
                map.put("width", 15000);
                titleList.add(map);
                row = sheet.createRow(2);
                for (int a = 0; a < titleList.size(); a++) {
                    sheet.setColumnWidth(a, Integer.parseInt(titleList.get(a).get("width").toString()));
                    sheet.setDefaultRowHeight((short) 450);
                    cell = row.createCell(a);
                    // 向单元格中写入数据
                    cell.setCellValue(titleList.get(a).get("title").toString());
                    cell.setCellStyle(titleContextCellStyle);
                }

                int index = 0; // 序号
                int beginIndex1 = 3; //用于计算合并单元格 【设备】一列，从第四行开始
                int beginIndex2 = 3; //用于计算合并单元格 【项目大类】一列，从第四行开始
                // 渲染数据
                List<PcbaDeviceParamType> pcbaDeviceParamTypeList = pcbaDeviceParamTypeDao.getPcbaDeviceParamTypeByPcbaDeviceTypeId(pcbaDeviceTypeId, null);
                if (pcbaDeviceParamTypeList != null && pcbaDeviceParamTypeList.size() > 0) {
                    for (int c = 0; c < pcbaDeviceParamTypeList.size(); c++) {
                        List<PcbaDeviceParam> pcbaDeviceParamList = pcbaDeviceParamDao.getAllPcbaDeviceParam(pcbaDeviceTypeId, pcbaDeviceParamTypeList.get(c).getPcbaDeviceParamTypeId(), null);
                        if (pcbaDeviceParamList != null && pcbaDeviceParamList.size() > 0) {
                            for (int d = 0; d < pcbaDeviceParamList.size(); d++) {
                                index++;
                                Row row_ = sheet.createRow(index + 2);

                                // 序号
                                Cell cell_ = row_.createCell(0);
//                                cell_.setCellValue(index);
//                                cell_.setCellStyle(bodyContextCellStyle);

                                // 设备
                                cell_ = row_.createCell(0);
                                cell_.setCellValue(pcbaDeviceTypeNameCn);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 品牌
                                cell_ = row_.createCell(1);
                                cell_.setCellValue(brandName);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 型号
                                cell_ = row_.createCell(2);
                                cell_.setCellValue(brandTypeName);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 备注
                                cell_ = row_.createCell(3);
                                cell_.setCellValue(notes);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 项目大类
                                cell_ = row_.createCell(4);
                                cell_.setCellValue(pcbaDeviceParamTypeList.get(c).getPcbaDeviceParamTypeName());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 设备能力评估项
                                cell_ = row_.createCell(5);
                                cell_.setCellValue(pcbaDeviceParamList.get(d).getPcbaDeviceParamNameCn());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 设备加工参数
                                cell_ = row_.createCell(6);
                                cell_.setCellValue(pcbaDeviceParamList.get(d).getPcbaDeviceParamValue());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 设计说明
                                /*1：普通文本
                                2.下拉选择
                                3：文件上传
                                4:  下拉多选
                                10：数值类型[整数]
                                11：数值类型[小数]
                                21：百分比
                                31：不限制 or NA or 数字
                                */
                                cell_ = row_.createCell(7);
                                cell_.setCellValue(pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 1 ? "普通文本" :
                                        (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 2 ? "下拉选择" + "(" + pcbaDeviceParamList.get(d).getPcbaDeviceParamOptions() + ")" :
                                                (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 3 ? "文件上传" :
                                                        (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 4 ? "下拉多选" + "(" + pcbaDeviceParamList.get(d).getPcbaDeviceParamOptions() + ")" :
                                                                (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 11 ? "整数" :
                                                                        (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 12 ? "小数" :
                                                                                (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 21 ? "百分比" :
                                                                                        (pcbaDeviceParamList.get(d).getPcbaDeviceParamFillType() == 31 ? "不限制 or NA or 数字" : ""))))))));
                                cell_.setCellStyle(bodyContextCellStyle);
                            }
                            // 合并第5列 【项目大类】
                            // System.out.println("pcbaDeviceParamList.size()=" + pcbaDeviceParamList.size());
                            if (pcbaDeviceParamList.size() > 1) {
                                if (index + 2 > beginIndex2) {
                                    sheet.addMergedRegion(new CellRangeAddress(beginIndex2, index + 2, 4, 4));
                                    beginIndex2 = index + 3;
                                }
                            } else {
                                beginIndex2 = index + 3;
                            }
                        }
                    }
                    // 合并第二列 【设备】第三列 第四列
                    //System.out.println("beginRow===" + beginIndex1);
                    //System.out.println("lastRow===" + (index + 2));
                    //if(pcbaDeviceParamTypeList.size() > 1){
                    if (index + 2 > beginIndex1) {
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 0, 0));
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 1, 1));
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 2, 2));
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 3, 3));
                        beginIndex1 = index + 3;
                    }
                    /*}else{
                        beginIndex2 = index + 3;
                    }*/
                }
            }
            String fileName = excelName + CommonUtils.getTimestamp() + ".xlsx";
            String pathPrefix = fileSaveUrl + "exportExcels\\";
            File folder = new File(pathPrefix);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String filePath = pathPrefix + fileName;
            // 导出Excel文件
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();

            byte[] bytedata = null;
            InputStream in = new FileInputStream(filePath);
            bytedata = new byte[in.available()];
            in.read(bytedata);
            in.close();
            java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
            String base64 = encoder.encodeToString(bytedata);

            Map<String, Object> resMap = new HashMap<>();
            resMap.put("base64", base64);
            resMap.put("fileName", fileName);
            return ResultUtil.success(resMap);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result exportDeviceResourceAndTechDeviceParamTable(String data) {
        try {
            List<PcbaDeviceResource> list = new ArrayList<>();
            List<PcbaDeviceResource> finalList = new ArrayList<>();
            if (data == null || "".equals(data)) {
                return ResultUtil.error(500, "缺少参数data", "Miss Param data", null);
            }
            JSONObject jsonObject = JSONObject.parseObject(data);
            String type = jsonObject.getString("type");
            if ("1".equals(type)) {
                // 按条件导出
                String deviceType2 = jsonObject.getString("deviceType2");
                String chooseBrandAndType2 = jsonObject.getString("chooseBrandAndType2");
                JSONArray jsonArray1 = JSONArray.parseArray(deviceType2);
                JSONArray jsonArray2 = JSONArray.parseArray(chooseBrandAndType2);
                //for (Object o1 : jsonArray1) {
                //Integer deviceTypeId = (Integer)o1;
                if (jsonArray2.size() > 0) {
                    for (Object o2 : jsonArray2) {
                        JSONArray jsonArray3 = (JSONArray) o2;
                        Integer pcbaDeviceTypeId = (Integer) jsonArray3.get(0);
                        Integer brandId = (Integer) jsonArray3.get(1);
                        Integer brandTypeId = (Integer) jsonArray3.get(2);

                        PcbaDeviceResource pcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsJudgeUnique(pcbaDeviceTypeId, brandId, brandTypeId, null, null);
                        if (pcbaDeviceResource != null) {
                            list.add(pcbaDeviceResource);
                        }
                    }
                }/*else{
                        List<PcbaDeviceResource> pcbaDeviceResource = pcbaDeviceResourceDao.getByConditions(deviceTypeId, null, null, null, null);
                        if(pcbaDeviceResource != null){
                            list.addAll(pcbaDeviceResource);
                        }
                    }*/
                /*}*/
            } else if ("2".equals(type)) {
                // 导出全部
                list = pcbaDeviceResourceDao.getAllByDeviceTypeAndSearch(null, null, null, null, null, null, null, null, null, null, null, null);
            } else if ("3".equals(type)) {
                // 导出选中
                JSONArray jsonArray = jsonObject.getJSONArray("list");
                for (int a = 0; a < jsonArray.size(); a++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(a);
                    String pcbaDeviceResourceId = jsonObject1.getString("pcbaDeviceResourceId");
                    PcbaDeviceResource pcbaDeviceResource = pcbaDeviceResourceDao.getById(Integer.parseInt(pcbaDeviceResourceId));
                    list.add(pcbaDeviceResource);
                }
            } else {
                return ResultUtil.error(500, "错误参数type", "Error Param type", null);
            }

            // 拿到list查询工艺参数
            for (PcbaDeviceResource pcbaDeviceResource : list) {
                Integer pcbaDeviceResourceId = pcbaDeviceResource.getPcbaDeviceResourceId();
                Integer pcbaDeviceTypeId = pcbaDeviceResource.getPcbaDeviceTypeId();
                pcbaDeviceResource.setBrand(brandDao.getBrandById(pcbaDeviceResource.getBrandId()));
                pcbaDeviceResource.setBrandType(brandTypeDao.getBrandTypeByIdAndBrand(pcbaDeviceResource.getBrandTypeId(), pcbaDeviceResource.getBrandId()));
                PcbaDeviceType pcbaDeviceType = pcbaDeviceTypeDao.getById(pcbaDeviceTypeId);
                if (pcbaDeviceType.getIsTechOwn() == 2) {
                    List<TechDeviceParamType> techDeviceParamTypeList = techDeviceParamTypeDao.getAllTechDeviceParamTypeByDeviceType(pcbaDeviceTypeId, null);
                    for (TechDeviceParamType techDeviceParamType : techDeviceParamTypeList) {
                        Integer techDeviceParamTypeId = techDeviceParamType.getTechDeviceParamTypeId();
                        List<TechDeviceParam> techDeviceParamList = techDeviceParamDao.getAllTechDeviceParam(pcbaDeviceTypeId, techDeviceParamTypeId, null);
                        for (TechDeviceParam techDeviceParam : techDeviceParamList) {
                            String techDeviceParamKey = techDeviceParam.getTechDeviceParamKey();
                            PcbaDeviceRelatedTechParam pcbaDeviceRelatedTechParam = pcbaDeviceRelatedTechParamDao.getPcbaDeviceRelatedTechParamByKeyAndDeviceResourceId(techDeviceParamKey, pcbaDeviceResourceId);
                            if (pcbaDeviceRelatedTechParam != null) {
                                techDeviceParam.setTechDeviceParamDeclareValue(pcbaDeviceRelatedTechParam.getTechDeviceParamValue());
                            }
                        }
                        techDeviceParamType.setTechDeviceParamList(techDeviceParamList);
                    }
                    pcbaDeviceType.setTechDeviceParamTypeList(techDeviceParamTypeList);
                    pcbaDeviceResource.setPcbaDeviceType(pcbaDeviceType);
                    finalList.add(pcbaDeviceResource);
                } else {
                    List<TechDeviceParamType> techDeviceParamTypeList = techDeviceParamTypeDao.getAllTechDeviceParamTypeByDeviceType(pcbaDeviceTypeId, null);
                    for (TechDeviceParamType techDeviceParamType : techDeviceParamTypeList) {
                        Integer techDeviceParamTypeId = techDeviceParamType.getTechDeviceParamTypeId();
                        List<TechDeviceParam> techDeviceParamList = techDeviceParamDao.getAllTechDeviceParam(pcbaDeviceTypeId, techDeviceParamTypeId, null);
                        for (TechDeviceParam techDeviceParam : techDeviceParamList) {
                            String techDeviceParamKey = techDeviceParam.getTechDeviceParamKey();
                            PcbaDeviceRelatedTechParam pcbaDeviceRelatedTechParam = pcbaDeviceRelatedTechParamDao.getPcbaDeviceRelatedTechParamByKeyAndDeviceResourceId(techDeviceParamKey, pcbaDeviceResourceId);
                            if (pcbaDeviceRelatedTechParam != null) {
                                techDeviceParam.setTechDeviceParamDeclareValue(pcbaDeviceRelatedTechParam.getTechDeviceParamValue());
                            }
                        }
                        techDeviceParamType.setTechDeviceParamList(techDeviceParamList);
                    }
                    pcbaDeviceType.setTechDeviceParamTypeList(techDeviceParamTypeList);
                    pcbaDeviceResource.setPcbaDeviceType(pcbaDeviceType);
                    finalList.add(pcbaDeviceResource);
                }
            }

            if (list.size() == 0) {
                return ResultUtil.error(500, "待导出数据为空", "Empty Data", null);
            }

            // 处理渲染excel
            String excelName = "设备工艺资源池";
            // 创建工作簿对象
            Workbook workbook = new XSSFWorkbook();
            for (PcbaDeviceResource pcbaDeviceResource : finalList) {
                String pcbaDeviceTypeNameCn = pcbaDeviceResource.getPcbaDeviceType().getPcbaDeviceTypeNameCn();
                String brandName = (pcbaDeviceResource.getBrand() != null && pcbaDeviceResource.getBrand().getBrandName() != null) ? pcbaDeviceResource.getBrand().getBrandName() : "";
                String brandTypeName = pcbaDeviceResource.getBrandType() != null ? pcbaDeviceResource.getBrandType().getBrandTypeName() : "";
                String notes = pcbaDeviceResource.getNotes();
                String sheetName = pcbaDeviceTypeNameCn;
                if (brandName != null && !"".equals(brandName) && brandTypeName != null && !"".equals(brandTypeName)) {
                    sheetName = sheetName + "-" + brandName + "-" + brandTypeName + '-' + notes;
                }
                // 创建工作表对象
                Sheet sheet = workbook.createSheet(CommonUtils.handleSheetName(sheetName));
                // 创建行和单元格对象
                Row row = sheet.createRow(0);

                CellStyle bigTitleContextCellStyle = workbook.createCellStyle();
                Font bigTitleFont = workbook.createFont();
                bigTitleFont.setBold(true);
                bigTitleFont.setFontHeightInPoints((short) 20);
                bigTitleContextCellStyle.setFont(bigTitleFont);
                bigTitleContextCellStyle.setAlignment(HorizontalAlignment.CENTER);
                bigTitleContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

                // 第一行大标题【设备基线能力参数反馈表】
                Cell cell = row.createCell(0);
                cell.setCellValue(excelName);
                cell.setCellStyle(bigTitleContextCellStyle);
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
                // 第二行 【注：模板内容不涉及，则填写NA】
                row = sheet.createRow(1);
                cell = row.createCell(0);
                cell.setCellValue("注：模板内容不涉及，则填写NA");
                sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 7));


                CellStyle bodyContextCellStyle = workbook.createCellStyle();
                DataFormat format = workbook.createDataFormat();
                bodyContextCellStyle.setDataFormat(format.getFormat("@"));
                bodyContextCellStyle.setBorderBottom(BorderStyle.THIN);
                bodyContextCellStyle.setBorderLeft(BorderStyle.THIN);
                bodyContextCellStyle.setBorderRight(BorderStyle.THIN);
                bodyContextCellStyle.setBorderTop(BorderStyle.THIN);
                bodyContextCellStyle.setAlignment(HorizontalAlignment.LEFT);
                bodyContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

                CellStyle titleContextCellStyle = workbook.createCellStyle();
                titleContextCellStyle.setBorderBottom(BorderStyle.THIN);
                titleContextCellStyle.setBorderLeft(BorderStyle.THIN);
                titleContextCellStyle.setBorderRight(BorderStyle.THIN);
                titleContextCellStyle.setBorderTop(BorderStyle.THIN);
                titleContextCellStyle.setAlignment(HorizontalAlignment.CENTER);
                titleContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                // 设置背景色为红色
                titleContextCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
                // 创建字体对象
                Font titleFont = workbook.createFont();
                // 设置字体颜色为蓝色
                titleFont.setColor(IndexedColors.WHITE.getIndex());
                titleFont.setBold(true);
                titleContextCellStyle.setFont(titleFont);
                // 设置填充类型为填充实体背景
                titleContextCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                List<Map<String, Object>> titleList = new ArrayList<>();

                Map<String, Object> map = new HashMap<>();
                map = new HashMap<>();
               /* map.put("title", "序号");
                map.put("width", 2000);
                titleList.add(map);*/
                map = new HashMap<>();
                map.put("title", "设备");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "品牌");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "型号");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "备注");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "项目大类");
                map.put("width", 6000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "设备能力评估项");
                map.put("width", 15000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "宣称能力值");
                map.put("width", 10000);
                titleList.add(map);
                map = new HashMap<>();
                map.put("title", "设计说明");
                map.put("width", 15000);
                titleList.add(map);
                row = sheet.createRow(2);
                for (int a = 0; a < titleList.size(); a++) {
                    sheet.setColumnWidth(a, Integer.parseInt(titleList.get(a).get("width").toString()));
                    sheet.setDefaultRowHeight((short) 450);
                    cell = row.createCell(a);
                    // 向单元格中写入数据
                    cell.setCellValue(titleList.get(a).get("title").toString());
                    cell.setCellStyle(titleContextCellStyle);
                }

                int index = 0; // 序号
                int beginIndex1 = 3; //用于计算合并单元格 【设备】一列，从第四行开始
                int beginIndex2 = 3; //用于计算合并单元格 【项目大类】一列，从第四行开始
                // 渲染数据
                List<TechDeviceParamType> techDeviceParamTypeList = pcbaDeviceResource.getPcbaDeviceType().getTechDeviceParamTypeList();
                if (techDeviceParamTypeList != null && techDeviceParamTypeList.size() > 0) {
                    for (int c = 0; c < techDeviceParamTypeList.size(); c++) {
                        List<TechDeviceParam> techDeviceParamList = techDeviceParamTypeList.get(c).getTechDeviceParamList();
                        if (techDeviceParamList != null && techDeviceParamList.size() > 0) {
                            for (int d = 0; d < techDeviceParamList.size(); d++) {
                                index++;
                                Row row_ = sheet.createRow(index + 2);

                                // 序号
                                Cell cell_ = row_.createCell(0);
                                /*cell_.setCellValue(index);
                                cell_.setCellStyle(bodyContextCellStyle);*/

                                // 设备
                                cell_ = row_.createCell(0);
                                cell_.setCellValue(pcbaDeviceTypeNameCn);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 品牌
                                cell_ = row_.createCell(1);
                                cell_.setCellValue(brandName);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 型号
                                cell_ = row_.createCell(2);
                                cell_.setCellValue(brandTypeName);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 备注
                                cell_ = row_.createCell(3);
                                cell_.setCellValue(notes);
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 项目大类
                                cell_ = row_.createCell(4);
                                cell_.setCellValue(techDeviceParamTypeList.get(c).getTechDeviceParamTypeName());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 设备能力评估项
                                cell_ = row_.createCell(5);
                                cell_.setCellValue(techDeviceParamList.get(d).getTechDeviceParamNameCn());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 设备加工参数
                                cell_ = row_.createCell(6);
                                cell_.setCellValue(techDeviceParamList.get(d).getTechDeviceParamDeclareValue());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 设计说明
                                /*1：普通文本
                                2.下拉选择
                                3：文件上传
                                4：来源基线
                                5：取多个基线最小值
                                10：数值类型[整数]
                                11：数值类型[小数]*/
                                cell_ = row_.createCell(7);
                                cell_.setCellValue(techDeviceParamList.get(d).getTechDeviceParamFillType() == 1 ? "普通文本" : (techDeviceParamList.get(d).getTechDeviceParamFillType() == 2 ? "下拉选择" + "(" + techDeviceParamList.get(d).getTechDeviceParamOptions() + ")" : (techDeviceParamList.get(d).getTechDeviceParamFillType() == 3 ? "文件上传" : (techDeviceParamList.get(d).getTechDeviceParamFillType()) == 11 ? "整数" : (techDeviceParamList.get(d).getTechDeviceParamFillType() == 12 ? "小数" : (techDeviceParamList.get(d).getTechDeviceParamFillType() == 4 ? "来源于基线值" : (techDeviceParamList.get(d).getTechDeviceParamFillType() == 5 ? "取多个基线最小值" : ""))))));
                                cell_.setCellStyle(bodyContextCellStyle);

                            }
                            // 合并第5列 【项目大类】
                            // System.out.println("pcbaDeviceParamList.size()=" + pcbaDeviceParamList.size());
                            if (techDeviceParamList.size() > 1) {
                                if (index + 2 > beginIndex2) {
                                    sheet.addMergedRegion(new CellRangeAddress(beginIndex2, index + 2, 4, 4));
                                    beginIndex2 = index + 3;
                                }
                            } else {
                                beginIndex2 = index + 3;
                            }
                        }
                    }
                    // 合并第二列 【设备】第三列 第四列
                    //System.out.println("beginRow===" + beginIndex1);
                    //System.out.println("lastRow===" + (index + 2));
                    //if(pcbaDeviceParamTypeList.size() > 1){
                    if (index + 2 > beginIndex1) {
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 0, 0));
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 1, 1));
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 2, 2));
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index + 2, 3, 3));
                        beginIndex1 = index + 3;
                    }
                    /*}else{
                        beginIndex2 = index + 3;
                    }*/
                }
            }
            String fileName = excelName + CommonUtils.getTimestamp() + ".xlsx";
            String pathPrefix = fileSaveUrl + "exportExcels\\";
            File folder = new File(pathPrefix);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String filePath = pathPrefix + fileName;
            // 导出Excel文件
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();

            byte[] bytedata = null;
            InputStream in = new FileInputStream(filePath);
            bytedata = new byte[in.available()];
            in.read(bytedata);
            in.close();
            java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
            String base64 = encoder.encodeToString(bytedata);

            Map<String, Object> resMap = new HashMap<>();
            resMap.put("list", list);
            resMap.put("base64", base64);
            resMap.put("fileName", fileName);
            return ResultUtil.success(resMap);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result importPcbaDeviceResourcesExcel(MultipartFile file) {
        try {
            if (file == null) {
                return ResultUtil.error(500, "缺少参数file", "Miss Param file", null);
            }
            // 1.得到一个输入流对象
            //FileInputStream in = FileConverterUtils.convertTo(file);
            InputStream inputStream = file.getInputStream();
            File f = FileConverterUtils.getTempFileFromInputStream(inputStream);
            // 2.将输入流对象进行解析 得到workbook对象
            //Workbook workbook = new XSSFWorkbook(in);
            Workbook workbook = WorkbookFactory.create(f);
            // 3.workbook中有几个工作簿
            int sheetNum = workbook.getNumberOfSheets();
            System.out.println("一共有" + sheetNum + "个工作簿");
            List<Object> list = new ArrayList<>();
            for (int a = 0; a < sheetNum; a++) {
                JSONObject jsonObject = new JSONObject();
                Sheet sheet = workbook.getSheetAt(a);
                int allRows = sheet.getLastRowNum() + 1;
                String sheetName = sheet.getSheetName();
                System.out.println("当前第" + (a + 1) + "sheetName：" + sheetName + "，总行数：" + allRows);

                // 循环判断每个sheet的模板是否正确，正确话的进行进一步解析，不正确的话直接返回错误
                Row row = sheet.getRow(2);
                String t1 = row.getCell(0) != null ? row.getCell(0).toString() : "";
                String t2 = row.getCell(1) != null ? row.getCell(1).toString() : "";
                String t3 = row.getCell(2) != null ? row.getCell(2).toString() : "";
                String t4 = row.getCell(3) != null ? row.getCell(3).toString() : "";
                String t5 = row.getCell(4) != null ? row.getCell(4).toString() : "";
                String t6 = row.getCell(5) != null ? row.getCell(5).toString() : "";
                String t7 = row.getCell(6) != null ? row.getCell(6).toString() : "";
                String t8 = row.getCell(7) != null ? row.getCell(7).toString() : "";
                if (t1.contains("设备") && t2.contains("品牌") && t3.contains("型号") && t4.contains("备注") && t5.contains("项目大类") && t6.contains("设备能力评估项") && t7.contains("设备加工能力参数") && t8.contains("设计说明")) {
                    // 表头符合的，循环获取每行数据
                    // 第四行可以读取到 设备、品牌、型号、备注 这些信息
                    Row rowV = sheet.getRow(3);
                    if (rowV != null) {
                        String pcbaDeviceTypeName = rowV.getCell(0) != null ? rowV.getCell(0).toString() : "";
                        String brandName = rowV.getCell(1) != null ? rowV.getCell(1).toString() : "";
                        String brandTypeName = rowV.getCell(2) != null ? rowV.getCell(2).toString() : "";
                        String notes = rowV.getCell(3) != null ? rowV.getCell(3).toString() : "";
                        PcbaDeviceType pcbaDeviceType = pcbaDeviceTypeDao.getPcbaDeviceTypeByNameCn(pcbaDeviceTypeName);
                        List<Brand> brandList = brandDao.getBrandByBrandName(brandName);
                        if (pcbaDeviceType == null) {
                            jsonObject.put("index", a + 1);
                            jsonObject.put("result", "fail");
                            jsonObject.put("message", "设备类型不在设备类型数据池(建议：联系管理员添加)");
                            jsonObject.put("action", "");
                        } else if (brandList.size() == 0) {
                            jsonObject.put("index", a + 1);
                            jsonObject.put("result", "fail");
                            jsonObject.put("message", "品牌不在品牌数据池(建议：联系管理员添加)");
                            jsonObject.put("action", "");
                        } else {
                            Integer brandId = brandList.get(0).getBrandId();
                            List<BrandType> brandTypeList = brandTypeDao.getBrandTypeByName(brandTypeName, brandId);
                            if (brandTypeList.size() == 0) {
                                jsonObject.put("index", a + 1);
                                jsonObject.put("result", "fail");
                                jsonObject.put("message", "型号不在当前品牌下的型号数据池(建议：联系管理员添加)");
                                jsonObject.put("action", "");
                            } else {
                                Integer brandTypeId = brandTypeList.get(0).getBrandTypeId();
                                // 判断 设备+品牌+型号+备注 是否已存在，不存在则完全新增后面参数，存在的话则执行update，update的内容需要用户二次确认
                                Integer pcbaDeviceTypeId = pcbaDeviceType.getPcbaDeviceTypeId();

                                PcbaDeviceResource pdr = new PcbaDeviceResource();
                                if ("".equals(notes)) {
                                    // 备注为空
                                    pdr = pcbaDeviceResourceDao.getByConditionsWithoutNotes(pcbaDeviceTypeId, brandId, brandTypeId, null);
                                } else {
                                    pdr = pcbaDeviceResourceDao.getByConditionsJudgeUnique(pcbaDeviceTypeId, brandId, brandTypeId, notes, null);
                                }

                                if (pdr != null) {
                                    // 查询参数结构
                                    List<PcbaDeviceParamType> pcbaDeviceParamTypeList = pcbaDeviceParamTypeDao.getPcbaDeviceParamTypeByPcbaDeviceTypeId(pcbaDeviceTypeId, null);
                                    for (PcbaDeviceParamType pcbaDeviceParamType : pcbaDeviceParamTypeList) {
                                        List<PcbaDeviceParam> allPcbaDeviceParam = pcbaDeviceParamDao.getAllPcbaDeviceParam(pcbaDeviceTypeId, pcbaDeviceParamType.getPcbaDeviceParamTypeId(), null);
                                        for (PcbaDeviceParam pcbaDeviceParam : allPcbaDeviceParam) {
                                            PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(pcbaDeviceParam.getPcbaDeviceParamKey(), pdr.getPcbaDeviceResourceId());
                                            if (pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId != null) {
                                                pcbaDeviceParam.setPcbaDeviceParamValue(pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId.getPcbaDeviceParamValue());
                                            }
                                        }
                                        pcbaDeviceParamType.setPcbaDeviceParamList(allPcbaDeviceParam);
                                    }

                                    // update 对比只显示不一样的
                                    // 查询项目大类、能力评估项、能力值，查询对应的key并且需要判断数据类型
                                    int needSubmitNums = 0;
                                    for (int b = 3; b < allRows; b++) {
                                        rowV = sheet.getRow(b);
                                        // 大类
                                        String dalei = "";
                                        // 获取合并单元格的数量
                                        int mergedRegions = sheet.getNumMergedRegions();
                                        for (int i = 0; i < mergedRegions; i++) {
                                            CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
                                            int firstRow = cellRangeAddress.getFirstRow();
                                            int lastRow = cellRangeAddress.getLastRow();
                                            int firstCol = cellRangeAddress.getFirstColumn();
                                            int lastCol = cellRangeAddress.getLastColumn();
                                            if (b >= firstRow && b <= lastRow && firstCol == 4 && lastCol == 4) {
                                                Cell cell = sheet.getRow(firstRow).getCell(4);
                                                dalei = cell.getStringCellValue();
                                                break;
                                            }
                                        }

                                        //能力项
                                        String v6 = rowV.getCell(5) != null ? rowV.getCell(5).toString() : "";
                                        //能力值
                                        String v7 = rowV.getCell(6) != null ? rowV.getCell(6).toString() : "";
                                        PcbaDeviceParamType pcbaDeviceParamType = pcbaDeviceParamTypeDao.getByPcbaDeviceTypeIdAndName(pcbaDeviceTypeId, dalei);
                                        if (pcbaDeviceParamType != null) {
                                            Integer pcbaDeviceParamTypeId = pcbaDeviceParamType.getPcbaDeviceParamTypeId();
                                            PcbaDeviceParam pcbaDeviceParam = pcbaDeviceParamDao.getByNameAndPcbaDeviceParamTypeId(pcbaDeviceParamTypeId, v6);
                                            if (pcbaDeviceParam != null) {
                                                for (PcbaDeviceParamType deviceParamType : pcbaDeviceParamTypeList) {
                                                    for (PcbaDeviceParam deviceParam : deviceParamType.getPcbaDeviceParamList()) {
//                                                        if("input_1690179996614".equals(deviceParam.getPcbaDeviceParamKey())){
//                                                            System.out.println(1);
//                                                        }
                                                        if (deviceParamType.getPcbaDeviceParamTypeId().equals(pcbaDeviceParamTypeId) && pcbaDeviceParam.getPcbaDeviceParamNameCn().equals(deviceParam.getPcbaDeviceParamNameCn())) {
                                                            if (CommonUtils.isNumeric(deviceParam.getPcbaDeviceParamValue()) && CommonUtils.isNumeric(v7)) {
                                                                if (Double.parseDouble(deviceParam.getPcbaDeviceParamValue()) == Double.parseDouble(v7)) {
                                                                    deviceParamType.getPcbaDeviceParamList().remove(deviceParam);
                                                                } else {
                                                                    needSubmitNums++;
                                                                    deviceParam.setPcbaDeviceOriginParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                    deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                    deviceParam.setSubmitPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                }
                                                            } else {
                                                                if (deviceParam.getPcbaDeviceParamValue() == null || "".equals(deviceParam.getPcbaDeviceParamValue()) || v7 == null || "".equals(v7)) {
                                                                    if (deviceParam.getPcbaDeviceParamValue() == null || "".equals(deviceParam.getPcbaDeviceParamValue())) {
                                                                        needSubmitNums++;
                                                                        deviceParam.setPcbaDeviceOriginParamValue("");
                                                                        deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                        deviceParam.setSubmitPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                    } else {
                                                                        needSubmitNums++;
                                                                        deviceParam.setPcbaDeviceOriginParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                        deviceParam.setPcbaDeviceParamValue("");
                                                                        deviceParam.setSubmitPcbaDeviceParamValue("");
                                                                    }
                                                                    //deviceParamType.getPcbaDeviceParamList().remove(deviceParam);
                                                                } else {
                                                                    if (deviceParam.getPcbaDeviceParamValue() != null && deviceParam.getPcbaDeviceParamValue().equals(v7)) {
                                                                        deviceParamType.getPcbaDeviceParamList().remove(deviceParam);
                                                                    } else {
                                                                        needSubmitNums++;
                                                                        deviceParam.setPcbaDeviceOriginParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                        deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                        deviceParam.setSubmitPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                    }
                                                                }
                                                            }
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                    JSONObject jo = new JSONObject();
                                    jo.put("data", pcbaDeviceParamTypeList);
                                    jo.put("pcbaDeviceTypeId", pcbaDeviceTypeId);
                                    jo.put("pcbaDeviceTypeName", pcbaDeviceTypeName);
                                    jo.put("brandId", brandId);
                                    jo.put("brandName", brandName);
                                    jo.put("brandTypeId", brandTypeId);
                                    jo.put("brandTypeName", brandTypeName);
                                    jo.put("notes", notes);

                                    jsonObject.put("index", a + 1);
                                    jsonObject.put("result", "success");
                                    jsonObject.put("message", "这个要执行update");
                                    jsonObject.put("data", jo);
                                    jsonObject.put("action", "update");
                                    jsonObject.put("needSubmitNums", needSubmitNums);
                                } else {
                                    if (pdr != null) {
                                        jsonObject.put("index", a + 1);
                                        jsonObject.put("result", "fail");
                                        jsonObject.put("message", "该设备类型+品牌+型号查询到多个，请添加备注后再尝试导入");
                                        jsonObject.put("action", "");
                                    } else {
                                        // 查询参数结构
                                        List<PcbaDeviceParamType> pcbaDeviceParamTypeList = pcbaDeviceParamTypeDao.getPcbaDeviceParamTypeByPcbaDeviceTypeId(pcbaDeviceTypeId, null);
                                        for (PcbaDeviceParamType pcbaDeviceParamType : pcbaDeviceParamTypeList) {
                                            List<PcbaDeviceParam> allPcbaDeviceParam = pcbaDeviceParamDao.getAllPcbaDeviceParam(pcbaDeviceTypeId, pcbaDeviceParamType.getPcbaDeviceParamTypeId(), null);
                                            pcbaDeviceParamType.setPcbaDeviceParamList(allPcbaDeviceParam);
                                        }

                                        // insert
                                        // 查询项目大类、能力评估项、能力值，查询对应的key并且需要判断数据类型
                                        for (int b = 3; b < allRows; b++) {
                                            rowV = sheet.getRow(b);
                                            // 大类
                                            String dalei = "";
                                            // 获取合并单元格的数量
                                            int mergedRegions = sheet.getNumMergedRegions();
                                            for (int i = 0; i < mergedRegions; i++) {
                                                CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
                                                int firstRow = cellRangeAddress.getFirstRow();
                                                int lastRow = cellRangeAddress.getLastRow();
                                                int firstCol = cellRangeAddress.getFirstColumn();
                                                int lastCol = cellRangeAddress.getLastColumn();
                                                if (b >= firstRow && b <= lastRow && firstCol == 4 && lastCol == 4) {
                                                    Cell cell = sheet.getRow(firstRow).getCell(4);
                                                    dalei = cell.getStringCellValue();
                                                    break;
                                                }
                                            }

                                            //能力项
                                            String v6 = rowV.getCell(5) != null ? rowV.getCell(5).toString() : "";
                                            //能力值
                                            String v7 = rowV.getCell(6) != null ? rowV.getCell(6).toString() : "";
                                            PcbaDeviceParamType pcbaDeviceParamType = pcbaDeviceParamTypeDao.getByPcbaDeviceTypeIdAndName(pcbaDeviceTypeId, dalei);
                                            if (pcbaDeviceParamType != null) {
                                                Integer pcbaDeviceParamTypeId = pcbaDeviceParamType.getPcbaDeviceParamTypeId();
                                                PcbaDeviceParam pcbaDeviceParam = pcbaDeviceParamDao.getByNameAndPcbaDeviceParamTypeId(pcbaDeviceParamTypeId, v6);
                                                if (pcbaDeviceParam != null) {
                                                    for (PcbaDeviceParamType deviceParamType : pcbaDeviceParamTypeList) {
                                                        for (PcbaDeviceParam deviceParam : deviceParamType.getPcbaDeviceParamList()) {
                                                            if (deviceParamType.getPcbaDeviceParamTypeId().equals(pcbaDeviceParamTypeId) && pcbaDeviceParam.getPcbaDeviceParamNameCn().equals(deviceParam.getPcbaDeviceParamNameCn())) {
                                                                deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                deviceParam.setSubmitPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        JSONObject jo = new JSONObject();
                                        jo.put("data", pcbaDeviceParamTypeList);
                                        jo.put("pcbaDeviceTypeId", pcbaDeviceTypeId);
                                        jo.put("pcbaDeviceTypeName", pcbaDeviceTypeName);
                                        jo.put("brandId", brandId);
                                        jo.put("brandName", brandName);
                                        jo.put("brandTypeId", brandTypeId);
                                        jo.put("brandTypeName", brandTypeName);
                                        jo.put("notes", notes);

                                        jsonObject.put("index", a + 1);
                                        jsonObject.put("result", "success");
                                        jsonObject.put("message", "这个要执行insert");
                                        jsonObject.put("data", jo);
                                        jsonObject.put("action", "insert");
                                        jsonObject.put("needSubmitNums", 0);
                                    }
                                }
                            }
                        }
                    } else {
                        jsonObject.put("index", a + 1);
                        jsonObject.put("result", "fail");
                        jsonObject.put("message", "数据为空");
                        jsonObject.put("action", "");
                    }
                } else {
                    jsonObject.put("index", a + 1);
                    jsonObject.put("result", "fail");
                    jsonObject.put("message", "模板不正确(建议：修改对应sheet模板)");
                    jsonObject.put("action", "");
                }
                list.add(jsonObject);
            }
            return ResultUtil.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result importPcbaDeviceResourcesExcelV2(MultipartFile file) {
        try {
            if (file == null) {
                return ResultUtil.error(500, "缺少参数file", "Miss Param file", null);
            }
            // 1.得到一个输入流对象
            //FileInputStream in = FileConverterUtils.convertTo(file);
            InputStream inputStream = file.getInputStream();
            File f = FileConverterUtils.getTempFileFromInputStream(inputStream);
            // 2.将输入流对象进行解析 得到workbook对象
            //Workbook workbook = new XSSFWorkbook(in);
            Workbook workbook = WorkbookFactory.create(f);
            // 3.workbook中有几个工作簿
            int sheetNum = workbook.getNumberOfSheets();
            System.out.println("一共有" + sheetNum + "个工作簿");
            List<Object> list = new ArrayList<>();
            for (int a = 0; a < sheetNum; a++) {
                JSONObject jsonObject = new JSONObject();
                Sheet sheet = workbook.getSheetAt(a);
                int allRows = sheet.getLastRowNum() + 1;
                String sheetName = sheet.getSheetName();
                System.out.println("当前第" + (a + 1) + "sheetName：" + sheetName + "，总行数：" + allRows);

                // 循环判断每个sheet的模板是否正确，正确话的进行进一步解析，不正确的话直接返回错误
                Row row = sheet.getRow(2);
                String t1 = row.getCell(0) != null ? row.getCell(0).toString() : "";
                String t2 = row.getCell(1) != null ? row.getCell(1).toString() : "";
                String t3 = row.getCell(2) != null ? row.getCell(2).toString() : "";
                String t4 = row.getCell(3) != null ? row.getCell(3).toString() : "";
                String t5 = row.getCell(4) != null ? row.getCell(4).toString() : "";
                String t6 = row.getCell(5) != null ? row.getCell(5).toString() : "";
                String t7 = row.getCell(6) != null ? row.getCell(6).toString() : "";
                String t8 = row.getCell(7) != null ? row.getCell(7).toString() : "";
                if (t1.contains("设备") && t2.contains("品牌") && t3.contains("型号") && t4.contains("备注") && t5.contains("项目大类") && t6.contains("设备能力评估项") && t7.contains("设备加工能力参数") && t8.contains("设计说明")) {
                    // 表头符合的，循环获取每行数据
                    // 第四行可以读取到 设备、品牌、型号、备注 这些信息
                    Row rowV = sheet.getRow(3);
                    if (rowV != null) {
                        String pcbaDeviceTypeName = rowV.getCell(0) != null ? rowV.getCell(0).toString() : "";
                        String brandName = rowV.getCell(1) != null ? (CommonUtils.isNumeric(rowV.getCell(1).toString()) ? rowV.getCell(1).toString().replace(".0", "") : rowV.getCell(1).toString()) : "";
                        String brandTypeName = rowV.getCell(2) != null ? (CommonUtils.isNumeric(rowV.getCell(2).toString()) ? rowV.getCell(2).toString().replace(".0", "") : rowV.getCell(2).toString()) : "";
                        String notes = rowV.getCell(3) != null ? rowV.getCell(3).toString() : "";
                        PcbaDeviceType pcbaDeviceType = pcbaDeviceTypeDao.getPcbaDeviceTypeByNameCn(pcbaDeviceTypeName);
                        List<Brand> brandList = brandDao.getBrandByBrandName(brandName);
                        if (pcbaDeviceType == null) {
                            jsonObject.put("index", a + 1);
                            jsonObject.put("result", "fail");
                            jsonObject.put("message", "设备类型不在设备类型数据池(建议：联系管理员添加)");
                            jsonObject.put("action", "submitNo");
                        } else if (brandList.size() == 0) {
                            jsonObject.put("index", a + 1);
                            jsonObject.put("result", "fail");
                            jsonObject.put("message", "品牌不在品牌数据池(建议：联系管理员添加)");
                            jsonObject.put("action", "submitNo");
                        } else {
                            Integer brandId = brandList.get(0).getBrandId();
                            List<BrandType> brandTypeList = brandTypeDao.getBrandTypeByName(brandTypeName, brandId);
                            if (brandTypeList.size() == 0) {
                                jsonObject.put("index", a + 1);
                                jsonObject.put("result", "fail");
                                jsonObject.put("message", "型号不在当前品牌下的型号数据池(建议：联系管理员添加)");
                                jsonObject.put("action", "submitNo");
                            } else {
                                Integer brandTypeId = brandTypeList.get(0).getBrandTypeId();
                                Integer pcbaDeviceTypeId = pcbaDeviceType.getPcbaDeviceTypeId();

                                // 构造解析excel的数据结构
                                List<PcbaDeviceParamType> pcbaDeviceParamTypeList2 = pcbaDeviceParamTypeDao.getPcbaDeviceParamTypeByPcbaDeviceTypeId(pcbaDeviceTypeId, null);
                                for (PcbaDeviceParamType pcbaDeviceParamType : pcbaDeviceParamTypeList2) {
                                    List<PcbaDeviceParam> allPcbaDeviceParam = pcbaDeviceParamDao.getAllPcbaDeviceParam(pcbaDeviceTypeId, pcbaDeviceParamType.getPcbaDeviceParamTypeId(), null);
//                                    for (PcbaDeviceParam pcbaDeviceParam : allPcbaDeviceParam) {
//                                        PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(pcbaDeviceParam.getPcbaDeviceParamKey(), pdr.getPcbaDeviceResourceId());
//                                        if(pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId != null){
//                                            pcbaDeviceParam.setPcbaDeviceParamValue(pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId.getPcbaDeviceParamValue());
//                                        }
//                                    }
                                    pcbaDeviceParamType.setPcbaDeviceParamList(allPcbaDeviceParam);
                                }

                                // update 对比只显示不一样的
                                // 查询项目大类、能力评估项、能力值，查询对应的key并且需要判断数据类型
                                for (int b = 3; b < allRows; b++) {
                                    rowV = sheet.getRow(b);
                                    // 大类
                                    String dalei = rowV.getCell(4) != null ? rowV.getCell(4).toString() : "";
                                    // 获取合并单元格的数量
                                    int mergedRegions = sheet.getNumMergedRegions();
                                    for (int i = 0; i < mergedRegions; i++) {
                                        CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
                                        int firstRow = cellRangeAddress.getFirstRow();
                                        int lastRow = cellRangeAddress.getLastRow();
                                        int firstCol = cellRangeAddress.getFirstColumn();
                                        int lastCol = cellRangeAddress.getLastColumn();
                                        if (b >= firstRow && b <= lastRow && firstCol == 4 && lastCol == 4) {
                                            Cell cell = sheet.getRow(firstRow).getCell(4);
                                            dalei = cell.getStringCellValue();
                                            break;
                                        }
                                    }

                                    //能力项
                                    String v6 = rowV.getCell(5) != null ? rowV.getCell(5).toString() : "";
                                    //能力值
                                    String v7 = rowV.getCell(6) != null ? rowV.getCell(6).toString() : "";
                                    PcbaDeviceParamType pcbaDeviceParamType = pcbaDeviceParamTypeDao.getByPcbaDeviceTypeIdAndName(pcbaDeviceTypeId, dalei);
                                    if (pcbaDeviceParamType != null) {
                                        Integer pcbaDeviceParamTypeId = pcbaDeviceParamType.getPcbaDeviceParamTypeId();
                                        PcbaDeviceParam pcbaDeviceParam = pcbaDeviceParamDao.getByNameAndPcbaDeviceParamTypeId(pcbaDeviceParamTypeId, v6);
                                        if (pcbaDeviceParam != null) {
                                            for (PcbaDeviceParamType deviceParamType : pcbaDeviceParamTypeList2) {
                                                for (PcbaDeviceParam deviceParam : deviceParamType.getPcbaDeviceParamList()) {
                                                    if (deviceParamType.getPcbaDeviceParamTypeId().equals(pcbaDeviceParamTypeId) && pcbaDeviceParam.getPcbaDeviceParamNameCn().equals(deviceParam.getPcbaDeviceParamNameCn())) {
                                                        if (CommonUtils.isNumeric(v7)) {
                                                            deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                        } else {
                                                            if (v7 == null || "".equals(v7)) {
                                                                deviceParam.setPcbaDeviceParamValue("");
                                                            } else {
                                                                deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                            }
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                List<PcbaDeviceResource> pcbaDeviceResourceList = pcbaDeviceResourceDao.getByConditions(pcbaDeviceTypeId, brandId, brandTypeId, null, null);

                                List<JSONObject> joList = new ArrayList<>();
                                for (PcbaDeviceResource pdr : pcbaDeviceResourceList) {
                                    if (pdr != null) {
                                        // 查询参数结构
                                        List<PcbaDeviceParamType> pcbaDeviceParamTypeList = pcbaDeviceParamTypeDao.getPcbaDeviceParamTypeByPcbaDeviceTypeId(pcbaDeviceTypeId, null);
                                        for (PcbaDeviceParamType pcbaDeviceParamType : pcbaDeviceParamTypeList) {
                                            List<PcbaDeviceParam> allPcbaDeviceParam = pcbaDeviceParamDao.getAllPcbaDeviceParam(pcbaDeviceTypeId, pcbaDeviceParamType.getPcbaDeviceParamTypeId(), null);
                                            for (PcbaDeviceParam pcbaDeviceParam : allPcbaDeviceParam) {
                                                PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(pcbaDeviceParam.getPcbaDeviceParamKey(), pdr.getPcbaDeviceResourceId());
                                                if (pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId != null) {
                                                    pcbaDeviceParam.setPcbaDeviceParamValue(pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId.getPcbaDeviceParamValue());
                                                }
                                            }
                                            pcbaDeviceParamType.setPcbaDeviceParamList(allPcbaDeviceParam);
                                        }

                                        // update 对比只显示不一样的
                                        // 查询项目大类、能力评估项、能力值，查询对应的key并且需要判断数据类型
                                        for (int b = 3; b < allRows; b++) {
                                            rowV = sheet.getRow(b);
                                            // 大类
                                            String dalei = rowV.getCell(4) != null ? rowV.getCell(4).toString() : "";
                                            // 获取合并单元格的数量
                                            int mergedRegions = sheet.getNumMergedRegions();
                                            for (int i = 0; i < mergedRegions; i++) {
                                                CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
                                                int firstRow = cellRangeAddress.getFirstRow();
                                                int lastRow = cellRangeAddress.getLastRow();
                                                int firstCol = cellRangeAddress.getFirstColumn();
                                                int lastCol = cellRangeAddress.getLastColumn();
                                                if (b >= firstRow && b <= lastRow && firstCol == 4 && lastCol == 4) {
                                                    Cell cell = sheet.getRow(firstRow).getCell(4);
                                                    dalei = cell.getStringCellValue();
                                                    break;
                                                }
                                            }

                                            //能力项
                                            String v6 = rowV.getCell(5) != null ? rowV.getCell(5).toString() : "";
                                            if(v6.contains("插件精度")){
                                                System.out.println("插件精度");
                                            }
                                            //能力值
                                            String v7 = rowV.getCell(6) != null ? rowV.getCell(6).toString() : "";
                                            PcbaDeviceParamType pcbaDeviceParamType = pcbaDeviceParamTypeDao.getByPcbaDeviceTypeIdAndName(pcbaDeviceTypeId, dalei);
                                            if (pcbaDeviceParamType != null) {

                                                Integer pcbaDeviceParamTypeId = pcbaDeviceParamType.getPcbaDeviceParamTypeId();
                                                PcbaDeviceParam pcbaDeviceParam = pcbaDeviceParamDao.getByNameAndPcbaDeviceParamTypeId(pcbaDeviceParamTypeId, v6);
                                                if (pcbaDeviceParam != null) {
                                                    for (PcbaDeviceParamType deviceParamType : pcbaDeviceParamTypeList) {
                                                        for (PcbaDeviceParam deviceParam : deviceParamType.getPcbaDeviceParamList()) {
                                                            if (deviceParamType.getPcbaDeviceParamTypeId().equals(pcbaDeviceParamTypeId) && pcbaDeviceParam.getPcbaDeviceParamNameCn().equals(deviceParam.getPcbaDeviceParamNameCn())) {
                                                                if (CommonUtils.isNumeric(deviceParam.getPcbaDeviceParamValue()) && CommonUtils.isNumeric(v7)) {
//                                                                    if(Double.parseDouble(deviceParam.getPcbaDeviceParamValue()) == Double.parseDouble(v7)){
//                                                                        //deviceParamType.getPcbaDeviceParamList().remove(deviceParam);
//                                                                    }else{
//                                                                        deviceParam.setPcbaDeviceOriginParamValue(deviceParam.getPcbaDeviceParamValue());
//                                                                        deviceParam.setSubmitPcbaDeviceParamValue(deviceParam.getPcbaDeviceParamValue());
//                                                                        deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
//                                                                    }
                                                                    deviceParam.setPcbaDeviceOriginParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                    deviceParam.setSubmitPcbaDeviceParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                    deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                } else {
                                                                    if (deviceParam.getPcbaDeviceParamValue() == null || "".equals(deviceParam.getPcbaDeviceParamValue()) || v7 == null || "".equals(v7)) {
                                                                        if (deviceParam.getPcbaDeviceParamValue() == null || "".equals(deviceParam.getPcbaDeviceParamValue())) {
                                                                            deviceParam.setPcbaDeviceOriginParamValue("");
                                                                            deviceParam.setSubmitPcbaDeviceParamValue("");
                                                                            deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                        } else {
                                                                            deviceParam.setPcbaDeviceOriginParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                            deviceParam.setSubmitPcbaDeviceParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                            deviceParam.setPcbaDeviceParamValue("");
                                                                        }
                                                                    } else {
//                                                                        if(deviceParam.getPcbaDeviceParamValue() != null && deviceParam.getPcbaDeviceParamValue().equals(v7)){
//                                                                            deviceParamType.getPcbaDeviceParamList().remove(deviceParam);
//                                                                        }else{
//                                                                            deviceParam.setPcbaDeviceOriginParamValue(deviceParam.getPcbaDeviceParamValue());
//                                                                            deviceParam.setSubmitPcbaDeviceParamValue(deviceParam.getPcbaDeviceParamValue());
//                                                                            deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
//                                                                        }
                                                                        deviceParam.setPcbaDeviceOriginParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                        deviceParam.setSubmitPcbaDeviceParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                        deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                    }
                                                                }
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        JSONObject jo = new JSONObject();
                                        jo.put("pcbaDeviceResourceId", pdr.getPcbaDeviceResourceId());
                                        jo.put("pcbaDeviceParamTypeList", pcbaDeviceParamTypeList);
                                        jo.put("notes", pdr.getNotes());
                                        jo.put("pcbaDeviceTypeId", pcbaDeviceTypeId);
                                        jo.put("pcbaDeviceTypeName", pcbaDeviceTypeName);
                                        jo.put("brandId", brandId);
                                        jo.put("brandName", brandName);
                                        jo.put("brandTypeId", brandTypeId);
                                        jo.put("brandTypeName", brandTypeName);

                                        joList.add(jo);
                                    }
                                }
                                JSONObject deviceInfo = new JSONObject();
                                deviceInfo.put("pcbaDeviceTypeId", pcbaDeviceTypeId);
                                deviceInfo.put("pcbaDeviceTypeName", pcbaDeviceTypeName);
                                deviceInfo.put("brandId", brandId);
                                deviceInfo.put("brandName", brandName);
                                deviceInfo.put("brandTypeId", brandTypeId);
                                deviceInfo.put("brandTypeName", brandTypeName);
                                deviceInfo.put("notes", notes);

                                jsonObject.put("deviceInfo", deviceInfo);
                                jsonObject.put("pcbaDeviceParamTypeList", pcbaDeviceParamTypeList2);
                                jsonObject.put("data", joList);
                                jsonObject.put("index", a + 1);
                                jsonObject.put("result", "success");
                                jsonObject.put("message", "解析成功");
                                jsonObject.put("action", "needSubmit");
                            }
                        }

                    } else {
                        jsonObject.put("index", a + 1);
                        jsonObject.put("result", "fail");
                        jsonObject.put("message", "数据为空");
                        jsonObject.put("action", "submitNo");
                    }
                } else {
                    jsonObject.put("index", a + 1);
                    jsonObject.put("result", "fail");
                    jsonObject.put("message", "模板不正确(建议：修改对应sheet模板)");
                    jsonObject.put("action", "submitNo");
                }
                list.add(jsonObject);
            }
            return ResultUtil.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result importPcbaDeviceResourcesBulkUpdateForParamAdd(MultipartFile file) {
        try {
            List<Integer> roleList = UserHeaderHolder.getRoleList();
            System.out.println("roleList.toString()=" + roleList.toString());
            if (roleList.contains(RoleName.SYS_ADMIN_ROLE_ID) || roleList.contains(RoleName.BASE_ADMIN_ROLE_ID) || roleList.contains(RoleName.TECH_ADMIN_ROLE_ID)) {
                if (file == null) {
                    return ResultUtil.error(500, "缺少参数file", "Miss Param file", null);
                }
                // 1.得到一个输入流对象
                //FileInputStream in = FileConverterUtils.convertTo(file);
                InputStream inputStream = file.getInputStream();
                File f = FileConverterUtils.getTempFileFromInputStream(inputStream);
                // 2.将输入流对象进行解析 得到workbook对象
                //Workbook workbook = new XSSFWorkbook(in);
                Workbook workbook = WorkbookFactory.create(f);
                // 3.workbook中有几个工作簿
                int sheetNum = workbook.getNumberOfSheets();
                System.out.println("一共有" + sheetNum + "个工作簿");
                if (sheetNum > 1) {
                    return ResultUtil.error(500, "只支持单个sheet的导入", "Only Support One Sheet", null);
                }
                List<Object> list = new ArrayList<>();
                JSONObject jsonObject = new JSONObject();
                int a = 0; // 第一个sheet
                Sheet sheet = workbook.getSheetAt(a);
                int allRows = sheet.getLastRowNum() + 1;
                String sheetName = sheet.getSheetName();
                System.out.println("当前第" + (a + 1) + "sheetName：" + sheetName + "，总行数：" + allRows);

                // 循环判断每个sheet的模板是否正确，正确话的进行进一步解析，不正确的话直接返回错误
                Row row = sheet.getRow(2);
                String t1 = row.getCell(0) != null ? row.getCell(0).toString() : "";
                String t2 = row.getCell(1) != null ? row.getCell(1).toString() : "";
                String t3 = row.getCell(2) != null ? row.getCell(2).toString() : "";
                String t4 = row.getCell(3) != null ? row.getCell(3).toString() : "";
                String t5 = row.getCell(4) != null ? row.getCell(4).toString() : "";
                String t6 = row.getCell(5) != null ? row.getCell(5).toString() : "";
                String t7 = row.getCell(6) != null ? row.getCell(6).toString() : "";
                String t8 = row.getCell(7) != null ? row.getCell(7).toString() : "";
                if (t1.contains("设备") && t2.contains("品牌") && t3.contains("型号") && t4.contains("备注") && t5.contains("项目大类") && t6.contains("设备能力评估项") && t7.contains("设备加工能力参数") && t8.contains("设计说明")) {
                    // 表头符合的，循环获取每行数据
                    // 第四行可以读取到 设备、品牌、型号、备注 这些信息
                    Row rowV = sheet.getRow(3);
                    if (rowV != null) {
                        String pcbaDeviceTypeName = rowV.getCell(0) != null ? rowV.getCell(0).toString() : "";
                        String brandName = rowV.getCell(1) != null ? rowV.getCell(1).toString() : "";
                        String brandTypeName = rowV.getCell(2) != null ? rowV.getCell(2).toString() : "";
                        String notes = rowV.getCell(3) != null ? rowV.getCell(3).toString() : "";
                        PcbaDeviceType pcbaDeviceType = pcbaDeviceTypeDao.getPcbaDeviceTypeByNameCn(pcbaDeviceTypeName);
                        if (pcbaDeviceType == null) {
                            jsonObject.put("index", a + 1);
                            jsonObject.put("result", "fail");
                            jsonObject.put("message", "设备类型不在设备类型数据池(建议：联系管理员添加)");
                            jsonObject.put("action", "submitNo");
                        } else {
                            Integer pcbaDeviceTypeId = pcbaDeviceType.getPcbaDeviceTypeId();

                            // 构造解析excel的数据结构
                            List<PcbaDeviceParamType> pcbaDeviceParamTypeList2 = pcbaDeviceParamTypeDao.getPcbaDeviceParamTypeByPcbaDeviceTypeId(pcbaDeviceTypeId, null);
                            for (PcbaDeviceParamType pcbaDeviceParamType : pcbaDeviceParamTypeList2) {
                                List<PcbaDeviceParam> allPcbaDeviceParam = pcbaDeviceParamDao.getAllPcbaDeviceParam(pcbaDeviceTypeId, pcbaDeviceParamType.getPcbaDeviceParamTypeId(), null);
                                pcbaDeviceParamType.setPcbaDeviceParamList(allPcbaDeviceParam);
                            }

                            // update 对比只显示不一样的
                            // 查询项目大类、能力评估项、能力值，查询对应的key并且需要判断数据类型
                            for (int b = 3; b < allRows; b++) {
                                rowV = sheet.getRow(b);
                                // 大类
                                String dalei = "";
                                // 获取合并单元格的数量
                                int mergedRegions = sheet.getNumMergedRegions();
                                for (int i = 0; i < mergedRegions; i++) {
                                    CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
                                    int firstRow = cellRangeAddress.getFirstRow();
                                    int lastRow = cellRangeAddress.getLastRow();
                                    int firstCol = cellRangeAddress.getFirstColumn();
                                    int lastCol = cellRangeAddress.getLastColumn();
                                    if (b >= firstRow && b <= lastRow && firstCol == 4 && lastCol == 4) {
                                        Cell cell = sheet.getRow(firstRow).getCell(4);
                                        dalei = cell.getStringCellValue();
                                        break;
                                    }
                                }

                                //能力项
                                String v6 = rowV.getCell(5) != null ? rowV.getCell(5).toString() : "";
                                //能力值
                                String v7 = rowV.getCell(6) != null ? rowV.getCell(6).toString() : "";
                                PcbaDeviceParamType pcbaDeviceParamType = pcbaDeviceParamTypeDao.getByPcbaDeviceTypeIdAndName(pcbaDeviceTypeId, dalei);
                                if (pcbaDeviceParamType != null) {
                                    Integer pcbaDeviceParamTypeId = pcbaDeviceParamType.getPcbaDeviceParamTypeId();
                                    PcbaDeviceParam pcbaDeviceParam = pcbaDeviceParamDao.getByNameAndPcbaDeviceParamTypeId(pcbaDeviceParamTypeId, v6);
                                    if (pcbaDeviceParam != null) {
                                        for (PcbaDeviceParamType deviceParamType : pcbaDeviceParamTypeList2) {
                                            for (PcbaDeviceParam deviceParam : deviceParamType.getPcbaDeviceParamList()) {
                                                if (deviceParamType.getPcbaDeviceParamTypeId().equals(pcbaDeviceParamTypeId) && pcbaDeviceParam.getPcbaDeviceParamNameCn().equals(deviceParam.getPcbaDeviceParamNameCn())) {
                                                    if (CommonUtils.isNumeric(v7)) {
                                                        deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                    } else {
                                                        if (v7 == null || "".equals(v7)) {
                                                            deviceParam.setPcbaDeviceParamValue("");
                                                        } else {
                                                            deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                        }
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            List<PcbaDeviceResource> pcbaDeviceResourceList = pcbaDeviceResourceDao.getByConditions(pcbaDeviceTypeId, null, null, null, null);
                            for (PcbaDeviceResource pcbaDeviceResource : pcbaDeviceResourceList) {
                                pcbaDeviceResource.setBrand(brandDao.getBrandById(pcbaDeviceResource.getBrandId()));
                                pcbaDeviceResource.setBrandType(brandTypeDao.getBrandTypeById(pcbaDeviceResource.getBrandTypeId()));
                            }

                            List<JSONObject> joList = new ArrayList<>();
                            for (PcbaDeviceResource pdr : pcbaDeviceResourceList) {
                                if (pdr != null) {
                                    // 查询参数结构
                                    List<PcbaDeviceParamType> pcbaDeviceParamTypeList = pcbaDeviceParamTypeDao.getPcbaDeviceParamTypeByPcbaDeviceTypeId(pcbaDeviceTypeId, null);
                                    for (PcbaDeviceParamType pcbaDeviceParamType : pcbaDeviceParamTypeList) {
                                        List<PcbaDeviceParam> allPcbaDeviceParam = pcbaDeviceParamDao.getAllPcbaDeviceParam(pcbaDeviceTypeId, pcbaDeviceParamType.getPcbaDeviceParamTypeId(), null);
                                        for (PcbaDeviceParam pcbaDeviceParam : allPcbaDeviceParam) {
                                            PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(pcbaDeviceParam.getPcbaDeviceParamKey(), pdr.getPcbaDeviceResourceId());
                                            if (pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId != null) {
                                                pcbaDeviceParam.setPcbaDeviceParamValue(pcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId.getPcbaDeviceParamValue());
                                            }
                                        }
                                        pcbaDeviceParamType.setPcbaDeviceParamList(allPcbaDeviceParam);
                                    }

                                    // update 对比只显示不一样的
                                    // 查询项目大类、能力评估项、能力值，查询对应的key并且需要判断数据类型
                                    for (int b = 3; b < allRows; b++) {
                                        rowV = sheet.getRow(b);
                                        // 大类
                                        String dalei = "";
                                        // 获取合并单元格的数量
                                        int mergedRegions = sheet.getNumMergedRegions();
                                        for (int i = 0; i < mergedRegions; i++) {
                                            CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
                                            int firstRow = cellRangeAddress.getFirstRow();
                                            int lastRow = cellRangeAddress.getLastRow();
                                            int firstCol = cellRangeAddress.getFirstColumn();
                                            int lastCol = cellRangeAddress.getLastColumn();
                                            if (b >= firstRow && b <= lastRow && firstCol == 4 && lastCol == 4) {
                                                Cell cell = sheet.getRow(firstRow).getCell(4);
                                                dalei = cell.getStringCellValue();
                                                break;
                                            }
                                        }

                                        //能力项
                                        String v6 = rowV.getCell(5) != null ? rowV.getCell(5).toString() : "";
                                        //能力值
                                        String v7 = rowV.getCell(6) != null ? rowV.getCell(6).toString() : "";
                                        PcbaDeviceParamType pcbaDeviceParamType = pcbaDeviceParamTypeDao.getByPcbaDeviceTypeIdAndName(pcbaDeviceTypeId, dalei);
                                        if (pcbaDeviceParamType != null) {

                                            Integer pcbaDeviceParamTypeId = pcbaDeviceParamType.getPcbaDeviceParamTypeId();
                                            PcbaDeviceParam pcbaDeviceParam = pcbaDeviceParamDao.getByNameAndPcbaDeviceParamTypeId(pcbaDeviceParamTypeId, v6);
                                            if (pcbaDeviceParam != null) {
                                                for (PcbaDeviceParamType deviceParamType : pcbaDeviceParamTypeList) {
                                                    for (PcbaDeviceParam deviceParam : deviceParamType.getPcbaDeviceParamList()) {
                                                        if (deviceParamType.getPcbaDeviceParamTypeId().equals(pcbaDeviceParamTypeId) && pcbaDeviceParam.getPcbaDeviceParamNameCn().equals(deviceParam.getPcbaDeviceParamNameCn())) {
                                                            if (CommonUtils.isNumeric(deviceParam.getPcbaDeviceParamValue()) && CommonUtils.isNumeric(v7)) {
                                                                deviceParam.setPcbaDeviceOriginParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                deviceParam.setSubmitPcbaDeviceParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                            } else {
                                                                if (deviceParam.getPcbaDeviceParamValue() == null || "".equals(deviceParam.getPcbaDeviceParamValue()) || v7 == null || "".equals(v7)) {
                                                                    if (deviceParam.getPcbaDeviceParamValue() == null || "".equals(deviceParam.getPcbaDeviceParamValue())) {
                                                                        deviceParam.setPcbaDeviceOriginParamValue("");
                                                                        deviceParam.setSubmitPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                        deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                    } else {
                                                                        deviceParam.setPcbaDeviceOriginParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                        deviceParam.setSubmitPcbaDeviceParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                        deviceParam.setPcbaDeviceParamValue("");
                                                                    }
                                                                } else {
                                                                    deviceParam.setPcbaDeviceOriginParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                    deviceParam.setSubmitPcbaDeviceParamValue(deviceParam.getPcbaDeviceParamValue());
                                                                    deviceParam.setPcbaDeviceParamValue(CommonUtils.removeZeros(v7));
                                                                }
                                                            }
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    JSONObject jo = new JSONObject();
                                    jo.put("pcbaDeviceResourceId", pdr.getPcbaDeviceResourceId());
                                    jo.put("pcbaDeviceParamTypeList", pcbaDeviceParamTypeList);
                                    jo.put("notes", pdr.getNotes());
                                    jo.put("pcbaDeviceTypeId", pcbaDeviceTypeId);
                                    jo.put("pcbaDeviceTypeName", pcbaDeviceTypeName);
                                    jo.put("brandName", pdr.getBrand().getBrandName());
                                    jo.put("brandId", pdr.getBrand().getBrandId());
                                    jo.put("brandTypeName", pdr.getBrandType().getBrandTypeName());
                                    jo.put("brandTypeId", pdr.getBrandType().getBrandTypeId());

                                    joList.add(jo);
                                }
                            }
                            JSONObject deviceInfo = new JSONObject();
                            deviceInfo.put("pcbaDeviceTypeId", pcbaDeviceTypeId);
                            deviceInfo.put("pcbaDeviceTypeName", pcbaDeviceTypeName);
                            deviceInfo.put("brandName", "");
                            deviceInfo.put("brandId", "");
                            deviceInfo.put("brandTypeName", "");
                            deviceInfo.put("brandTypeId", "");
                            deviceInfo.put("notes", notes);

                            jsonObject.put("deviceInfo", deviceInfo);
                            jsonObject.put("pcbaDeviceParamTypeList", pcbaDeviceParamTypeList2);
                            jsonObject.put("data", joList);
                            jsonObject.put("index", a + 1);
                            jsonObject.put("result", "success");
                            jsonObject.put("message", "解析成功");
                            jsonObject.put("action", "needSubmit");
                        }
                    } else {
                        jsonObject.put("index", a + 1);
                        jsonObject.put("result", "fail");
                        jsonObject.put("message", "数据为空");
                        jsonObject.put("action", "submitNo");
                    }
                } else {
                    jsonObject.put("index", a + 1);
                    jsonObject.put("result", "fail");
                    jsonObject.put("message", "模板不正确(建议：修改对应sheet模板)");
                    jsonObject.put("action", "submitNo");
                }
                list.add(jsonObject);
                return ResultUtil.success(list);
            } else {
                return ResultUtil.error(500, "无权限", "No Permission", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result submitImportPcbaDeviceResourcesBulkUpdateForParamAdd(String data) {
        try {
            Date d = new Date();
            String userId = UserHeaderHolder.getUserId();
            List<PcbaDeviceResource> addPcbaDeviceResourceList = new ArrayList<>();
            List<PcbaDeviceRelatedDeviceParam> addPcbaDeviceRelatedDeviceParamList = new ArrayList<>();
            List<PcbaDeviceRelatedDeviceParam> oldPcbaDeviceRelatedDeviceParamList = new ArrayList<>();
            List<PcbaDeviceRelatedDeviceParam> newPcbaDeviceRelatedDeviceParamList = new ArrayList<>();
            JSONArray jsonArray = JSONArray.parseArray(data);
            for (int a = 0; a < jsonArray.size(); a++) {
                JSONObject jsonObject = jsonArray.getJSONObject(a);
                String result = jsonObject.get("result") != null ? jsonObject.get("result").toString() : "";
                if ("success".equals(result)) {
                    String resourceDataStr = jsonObject.get("data").toString();
                    JSONArray resourceJa = JSONArray.parseArray(resourceDataStr);
                    for (int aa = 0; aa < resourceJa.size(); aa++) {
                        JSONObject resourceJo = resourceJa.getJSONObject(aa);
                        String brandId = resourceJo.get("brandId").toString();
                        String brandTypeId = resourceJo.get("brandTypeId").toString();
                        String notes = resourceJo.get("notes").toString();
                        String pcbaDeviceTypeId = resourceJo.get("pcbaDeviceTypeId").toString();
                        String needSubmitNum = resourceJo.get("needSubmitNum") != null ? resourceJo.get("needSubmitNum").toString() : "";

                        if (Integer.parseInt(needSubmitNum) > 0) {
                            // update
                            PcbaDeviceResource pcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsJudgeUnique(Integer.parseInt(pcbaDeviceTypeId), Integer.parseInt(brandId), Integer.parseInt(brandTypeId), notes, null);
                            if (pcbaDeviceResource != null) {
                                Integer pcbaDeviceResourceId = pcbaDeviceResource.getPcbaDeviceResourceId();

                                // 设备资源的 基线 审核状态修改为 待提交审核
                                //pcbaDeviceResourceDao.updateAuditStatusBaseWithSubmitter(pcbaDeviceResourceId, 4, Integer.parseInt(userId));

                                JSONArray pcbaDeviceParamTypeList = resourceJo.getJSONArray("pcbaDeviceParamTypeList");
                                for (int aaa = 0; aaa < pcbaDeviceParamTypeList.size(); aaa++) {
                                    JSONArray paramsListJa = pcbaDeviceParamTypeList.getJSONObject(aaa).getJSONArray("pcbaDeviceParamList");
                                    for (int b = 0; b < paramsListJa.size(); b++) {
                                        JSONObject jo = paramsListJa.getJSONObject(b);
                                        String pcbaDeviceParamKey = jo.getString("pcbaDeviceParamKey");
                                        String submitPcbaDeviceParamValue = jo.getString("submitPcbaDeviceParamValue");

                                        PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(pcbaDeviceParamKey, pcbaDeviceResourceId);
                                        if (pcbaDeviceRelatedDeviceParam != null) {
                                            // update
                                            oldPcbaDeviceRelatedDeviceParamList.add(pcbaDeviceRelatedDeviceParam);

                                            PcbaDeviceRelatedDeviceParam updatePcbaDeviceRelatedDeviceParam = new PcbaDeviceRelatedDeviceParam();
                                            updatePcbaDeviceRelatedDeviceParam.setPcbaDeviceRelatedDeviceParamId(pcbaDeviceRelatedDeviceParam.getPcbaDeviceRelatedDeviceParamId());
                                            updatePcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValue(submitPcbaDeviceParamValue);
                                            updatePcbaDeviceRelatedDeviceParam.setUpdateTime(d);
                                            pcbaDeviceRelatedDeviceParamDao.updateDeviceRelatedParam(updatePcbaDeviceRelatedDeviceParam);

                                            newPcbaDeviceRelatedDeviceParamList.add(updatePcbaDeviceRelatedDeviceParam);
                                        } else {

                                            //insert
                                            PcbaDeviceRelatedDeviceParam addPcbaDeviceRelatedDeviceParam = new PcbaDeviceRelatedDeviceParam();
                                            addPcbaDeviceRelatedDeviceParam.setPcbaDeviceResourceId(pcbaDeviceResourceId);
                                            addPcbaDeviceRelatedDeviceParam.setPcbaDeviceParamKey(pcbaDeviceParamKey);
                                            addPcbaDeviceRelatedDeviceParam.setPcbaDeviceTypeId(Integer.parseInt(pcbaDeviceTypeId));
                                            addPcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValue(submitPcbaDeviceParamValue);
                                            addPcbaDeviceRelatedDeviceParam.setUpdateTime(d);

                                            pcbaDeviceRelatedDeviceParamDao.addDeviceRelatedParam(addPcbaDeviceRelatedDeviceParam);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }

            // 操作日志
            if (addPcbaDeviceResourceList.size() > 0) {
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 2, d, null, JSONObject.toJSONString(addPcbaDeviceResourceList)));
            }
            if (addPcbaDeviceRelatedDeviceParamList.size() > 0) {
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 2, d, null, JSONObject.toJSONString(addPcbaDeviceRelatedDeviceParamList)));
            }
            if (oldPcbaDeviceRelatedDeviceParamList.size() > 0 || newPcbaDeviceRelatedDeviceParamList.size() > 0) {
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 2, d, JSONObject.toJSONString(oldPcbaDeviceRelatedDeviceParamList), JSONObject.toJSONString(newPcbaDeviceRelatedDeviceParamList)));
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result submitImportPcbaDeviceResourcesData(String data) {
        try {
            Date d = new Date();
            String userId = UserHeaderHolder.getUserId();
            List<PcbaDeviceResource> addPcbaDeviceResourceList = new ArrayList<>();
            List<PcbaDeviceRelatedDeviceParam> addPcbaDeviceRelatedDeviceParamList = new ArrayList<>();
            List<PcbaDeviceRelatedDeviceParam> oldPcbaDeviceRelatedDeviceParamList = new ArrayList<>();
            List<PcbaDeviceRelatedDeviceParam> newPcbaDeviceRelatedDeviceParamList = new ArrayList<>();
            JSONArray jsonArray = JSONArray.parseArray(data);
            for (int a = 0; a < jsonArray.size(); a++) {
                JSONObject jsonObject = jsonArray.getJSONObject(a);
                String result = jsonObject.get("result") != null ? jsonObject.get("result").toString() : "";
                String needSubmitNums = jsonObject.get("needSubmitNums") != null ? jsonObject.get("needSubmitNums").toString() : "";
                String action = jsonObject.get("action") != null ? jsonObject.get("action").toString() : "";

                if ("success".equals(result)) {
                    String resourceDataStr = jsonObject.get("data").toString();
                    JSONObject resourceJo = JSONObject.parseObject(resourceDataStr);
                    String brandId = resourceJo.get("brandId").toString();
                    String brandTypeId = resourceJo.get("brandTypeId").toString();
                    String notes = resourceJo.get("notes").toString();
                    String pcbaDeviceTypeId = resourceJo.get("pcbaDeviceTypeId").toString();
                    if ("insert".equals(action)) {
                        // insert
                        PcbaDeviceResource addPcbaDeviceResource = new PcbaDeviceResource();
                        addPcbaDeviceResource.setPcbaDeviceTypeId(Integer.parseInt(pcbaDeviceTypeId));
                        addPcbaDeviceResource.setBrandId(Integer.parseInt(brandId));
                        addPcbaDeviceResource.setBrandTypeId(Integer.parseInt(brandTypeId));
                        addPcbaDeviceResource.setCreateTime(d);
                        addPcbaDeviceResource.setSort(100);
                        addPcbaDeviceResource.setStatus(1);
                        addPcbaDeviceResource.setNotes(notes);
                        addPcbaDeviceResource.setIsFilledBaseParams(2);
                        addPcbaDeviceResource.setIsFilledTechParams(2);
                        addPcbaDeviceResource.setAuditStatusBase(4);
                        addPcbaDeviceResource.setAuditStatusTech(4);
                        pcbaDeviceResourceDao.addPcbaDeviceResource(addPcbaDeviceResource);

                        addPcbaDeviceResourceList.add(addPcbaDeviceResource);

                        JSONArray paramsDataJa = resourceJo.getJSONArray("data");
                        for (int c = 0; c < paramsDataJa.size(); c++) {
                            JSONObject paramsDataJo = paramsDataJa.getJSONObject(c);

                            JSONArray paramsListJa = paramsDataJo.getJSONArray("pcbaDeviceParamList");
                            for (int b = 0; b < paramsListJa.size(); b++) {
                                JSONObject jo = paramsListJa.getJSONObject(b);
                                String pcbaDeviceParamKey = jo.getString("pcbaDeviceParamKey");
                                String submitPcbaDeviceParamValue = jo.getString("submitPcbaDeviceParamValue");

                                PcbaDeviceRelatedDeviceParam addPcbaDeviceRelatedDeviceParam = new PcbaDeviceRelatedDeviceParam();
                                addPcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValue(submitPcbaDeviceParamValue);
                                addPcbaDeviceRelatedDeviceParam.setCreateTime(d);
                                addPcbaDeviceRelatedDeviceParam.setPcbaDeviceResourceId(addPcbaDeviceResource.getPcbaDeviceResourceId());
                                addPcbaDeviceRelatedDeviceParam.setPcbaDeviceParamKey(pcbaDeviceParamKey);
                                addPcbaDeviceRelatedDeviceParam.setPcbaDeviceTypeId(Integer.parseInt(pcbaDeviceTypeId));
                                pcbaDeviceRelatedDeviceParamDao.addDeviceRelatedParam(addPcbaDeviceRelatedDeviceParam);

                                addPcbaDeviceRelatedDeviceParamList.add(addPcbaDeviceRelatedDeviceParam);
                            }
                        }
                    } else {
                        if (Integer.parseInt(needSubmitNums) > 0) {
                            // update
                            PcbaDeviceResource pcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsJudgeUnique(Integer.parseInt(pcbaDeviceTypeId), Integer.parseInt(brandId), Integer.parseInt(brandTypeId), notes, null);
                            if (pcbaDeviceResource != null) {
                                Integer pcbaDeviceResourceId = pcbaDeviceResource.getPcbaDeviceResourceId();

                                // 设备资源的 基线 审核状态修改为 待提交审核
                                pcbaDeviceResourceDao.updateAuditStatusBaseWithSubmitter(pcbaDeviceResourceId, 4, Integer.parseInt(userId));

                                JSONArray paramsDataJa = resourceJo.getJSONArray("data");
                                for (int c = 0; c < paramsDataJa.size(); c++) {
                                    JSONObject paramsDataJo = paramsDataJa.getJSONObject(c);

                                    JSONArray paramsListJa = paramsDataJo.getJSONArray("pcbaDeviceParamList");
                                    for (int b = 0; b < paramsListJa.size(); b++) {
                                        JSONObject jo = paramsListJa.getJSONObject(b);
                                        String pcbaDeviceParamKey = jo.getString("pcbaDeviceParamKey");
                                        String submitPcbaDeviceParamValue = jo.getString("submitPcbaDeviceParamValue");

                                        PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(pcbaDeviceParamKey, pcbaDeviceResourceId);
                                        if (pcbaDeviceRelatedDeviceParam != null) {
                                            // update
                                            oldPcbaDeviceRelatedDeviceParamList.add(pcbaDeviceRelatedDeviceParam);

                                            PcbaDeviceRelatedDeviceParam updatePcbaDeviceRelatedDeviceParam = new PcbaDeviceRelatedDeviceParam();
                                            updatePcbaDeviceRelatedDeviceParam.setPcbaDeviceRelatedDeviceParamId(pcbaDeviceRelatedDeviceParam.getPcbaDeviceRelatedDeviceParamId());
                                            updatePcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValue(submitPcbaDeviceParamValue);
                                            updatePcbaDeviceRelatedDeviceParam.setUpdateTime(d);
                                            pcbaDeviceRelatedDeviceParamDao.updateDeviceRelatedParam(updatePcbaDeviceRelatedDeviceParam);

                                            newPcbaDeviceRelatedDeviceParamList.add(updatePcbaDeviceRelatedDeviceParam);
                                        } else {

                                            //insert
                                            PcbaDeviceRelatedDeviceParam addPcbaDeviceRelatedDeviceParam = new PcbaDeviceRelatedDeviceParam();
                                            addPcbaDeviceRelatedDeviceParam.setPcbaDeviceResourceId(pcbaDeviceResourceId);
                                            addPcbaDeviceRelatedDeviceParam.setPcbaDeviceParamKey(pcbaDeviceParamKey);
                                            addPcbaDeviceRelatedDeviceParam.setPcbaDeviceTypeId(Integer.parseInt(pcbaDeviceTypeId));
                                            addPcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValue(submitPcbaDeviceParamValue);
                                            addPcbaDeviceRelatedDeviceParam.setUpdateTime(d);

                                            pcbaDeviceRelatedDeviceParamDao.addDeviceRelatedParam(addPcbaDeviceRelatedDeviceParam);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }
            // 操作日志
            if (addPcbaDeviceResourceList.size() > 0) {
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 2, d, null, JSONObject.toJSONString(addPcbaDeviceResourceList)));
            }
            if (addPcbaDeviceRelatedDeviceParamList.size() > 0) {
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 2, d, null, JSONObject.toJSONString(addPcbaDeviceRelatedDeviceParamList)));
            }
            if (oldPcbaDeviceRelatedDeviceParamList.size() > 0 || newPcbaDeviceRelatedDeviceParamList.size() > 0) {
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 2, d, JSONObject.toJSONString(oldPcbaDeviceRelatedDeviceParamList), JSONObject.toJSONString(newPcbaDeviceRelatedDeviceParamList)));
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result importTechDeviceResourcesExcel(MultipartFile file) {
        try {
            if (file == null) {
                return ResultUtil.error(500, "缺少参数file", "Miss Param file", null);
            }
            // 1.得到一个输入流对象
            //FileInputStream in = FileConverterUtils.convertTo(file);
            InputStream inputStream = file.getInputStream();
            File f = FileConverterUtils.getTempFileFromInputStream(inputStream);
            // 2.将输入流对象进行解析 得到workbook对象
            //Workbook workbook = new XSSFWorkbook(in);
            Workbook workbook = WorkbookFactory.create(f);
            // 3.workbook中有几个工作簿
            int sheetNum = workbook.getNumberOfSheets();
            System.out.println("一共有" + sheetNum + "个工作簿");
            List<Object> list = new ArrayList<>();
            for (int a = 0; a < sheetNum; a++) {
                JSONObject jsonObject = new JSONObject();
                Sheet sheet = workbook.getSheetAt(a);
                int allRows = sheet.getLastRowNum() + 1;
                String sheetName = sheet.getSheetName();
                System.out.println("当前第" + (a + 1) + "sheetName：" + sheetName + "，总行数：" + allRows);

                // 循环判断每个sheet的模板是否正确，正确话的进行进一步解析，不正确的话直接返回错误
                Row row = sheet.getRow(2);
                String t1 = row.getCell(0) != null ? row.getCell(0).toString() : "";
                String t2 = row.getCell(1) != null ? row.getCell(1).toString() : "";
                String t3 = row.getCell(2) != null ? row.getCell(2).toString() : "";
                String t4 = row.getCell(3) != null ? row.getCell(3).toString() : "";
                String t5 = row.getCell(4) != null ? row.getCell(4).toString() : "";
                String t6 = row.getCell(5) != null ? row.getCell(5).toString() : "";
                String t7 = row.getCell(6) != null ? row.getCell(6).toString() : "";
                String t8 = row.getCell(7) != null ? row.getCell(7).toString() : "";
                if (t1.contains("设备") && t2.contains("品牌") && t3.contains("型号") && t4.contains("备注") && t5.contains("项目大类") && t6.contains("设备能力评估项") && t7.contains("宣称能力值") && t8.contains("设计说明")) {
                    // 表头符合的，循环获取每行数据
                    // 第四行可以读取到 设备、品牌、型号、备注 这些信息
                    Row rowV = sheet.getRow(3);
                    if (rowV != null) {
                        String pcbaDeviceTypeName = rowV.getCell(0) != null ? rowV.getCell(0).toString() : "";
                        String brandName = rowV.getCell(1) != null ? rowV.getCell(1).toString() : "";
                        String brandTypeName = rowV.getCell(2) != null ? rowV.getCell(2).toString() : "";
                        String notes = rowV.getCell(3) != null ? rowV.getCell(3).toString() : "";
                        PcbaDeviceType pcbaDeviceType = pcbaDeviceTypeDao.getPcbaDeviceTypeByNameCn(pcbaDeviceTypeName);
                        List<Brand> brandList = brandDao.getBrandByBrandName(brandName);
                        if (pcbaDeviceType == null) {
                            jsonObject.put("index", a + 1);
                            jsonObject.put("result", "fail");
                            jsonObject.put("message", "设备类型不在设备类型数据池(建议：联系管理员添加)");
                            jsonObject.put("action", "");
                        } else if (brandList.size() == 0) {
                            jsonObject.put("index", a + 1);
                            jsonObject.put("result", "fail");
                            jsonObject.put("message", "品牌不在品牌数据池(建议：联系管理员添加)");
                            jsonObject.put("action", "");
                        } else {
                            Integer brandId = brandList.get(0).getBrandId();
                            List<BrandType> brandTypeList = brandTypeDao.getBrandTypeByName(brandTypeName, brandId);
                            if (brandTypeList.size() == 0) {
                                jsonObject.put("index", a + 1);
                                jsonObject.put("result", "fail");
                                jsonObject.put("message", "型号不在此品牌下的型号数据池(建议：联系管理员添加)");
                                jsonObject.put("action", "");
                            } else {
                                Integer brandTypeId = brandTypeList.get(0).getBrandTypeId();
                                // 判断 设备+品牌+型号+备注 是否已存在，不存在则完全新增后面参数，存在的话则执行update，update的内容需要用户二次确认
                                Integer pcbaDeviceTypeId = pcbaDeviceType.getPcbaDeviceTypeId();
                                List<PcbaDeviceResource> pcbaDeviceResourceList = pcbaDeviceResourceDao.getAllByDeviceTypeAndSearch(null, pcbaDeviceTypeId, null, null, null, brandId, brandTypeId, null, null, notes, null, null);

                                if (pcbaDeviceResourceList.size() == 1) {
                                    if (pcbaDeviceResourceList.get(0).getIsFilledBaseParams() != 1) {
                                        jsonObject.put("index", a + 1);
                                        jsonObject.put("result", "fail");
                                        jsonObject.put("message", "该设备资源的基线参数没有完善");
                                        jsonObject.put("action", "");
                                    } else {
                                        // 查询参数结构
                                        List<TechDeviceParamType> techDeviceParamTypeList = techDeviceParamTypeDao.getAllTechDeviceParamTypeByDeviceType(pcbaDeviceTypeId, null);
                                        for (TechDeviceParamType techDeviceParamType : techDeviceParamTypeList) {
                                            List<TechDeviceParam> allTechDeviceParam = techDeviceParamDao.getAllTechDeviceParam(pcbaDeviceTypeId, techDeviceParamType.getTechDeviceParamTypeId(), null);
                                            for (TechDeviceParam techDeviceParam : allTechDeviceParam) {
                                                PcbaDeviceRelatedTechParam pcbaDeviceRelatedTechParamByKeyAndDeviceResourceId = pcbaDeviceRelatedTechParamDao.getPcbaDeviceRelatedTechParamByKeyAndDeviceResourceId(techDeviceParam.getTechDeviceParamKey(), pcbaDeviceResourceList.get(0).getPcbaDeviceResourceId());
                                                if (pcbaDeviceRelatedTechParamByKeyAndDeviceResourceId != null) {
                                                    techDeviceParam.setTechDeviceParamDeclareValue(pcbaDeviceRelatedTechParamByKeyAndDeviceResourceId.getTechDeviceParamValue());
                                                }
                                            }
                                            techDeviceParamType.setTechDeviceParamList(allTechDeviceParam);
                                        }

                                        // update 对比只显示不一样的
                                        // 查询项目大类、能力评估项、能力值，查询对应的key并且需要判断数据类型
                                        int needSubmitNums = 0;
                                        for (int b = 3; b < allRows; b++) {
                                            rowV = sheet.getRow(b);
                                            // 大类
                                            String dalei = "";
                                            // 获取合并单元格的数量
                                            int mergedRegions = sheet.getNumMergedRegions();
                                            for (int i = 0; i < mergedRegions; i++) {
                                                CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
                                                int firstRow = cellRangeAddress.getFirstRow();
                                                int lastRow = cellRangeAddress.getLastRow();
                                                int firstCol = cellRangeAddress.getFirstColumn();
                                                int lastCol = cellRangeAddress.getLastColumn();
                                                if (b >= firstRow && b <= lastRow && firstCol == 4 && lastCol == 4) {
                                                    Cell cell = sheet.getRow(firstRow).getCell(4);
                                                    dalei = cell.getStringCellValue();
                                                    break;
                                                }
                                            }

                                            //能力项
                                            String v6 = rowV.getCell(5) != null ? rowV.getCell(5).toString() : "";
                                            //能力值
                                            String v7 = rowV.getCell(6) != null ? rowV.getCell(6).toString() : "";
                                            TechDeviceParamType techDeviceParamType = techDeviceParamTypeDao.getByTechDeviceTypeIdAndName(pcbaDeviceTypeId, dalei);
                                            if (techDeviceParamType != null) {
                                                Integer techDeviceParamTypeId = techDeviceParamType.getTechDeviceParamTypeId();
                                                TechDeviceParam techDeviceParam = techDeviceParamDao.getByNameAndTechDeviceParamTypeId(techDeviceParamTypeId, v6);
                                                if (techDeviceParam != null) {
                                                    for (TechDeviceParamType deviceParamType : techDeviceParamTypeList) {
                                                        for (TechDeviceParam deviceParam : deviceParamType.getTechDeviceParamList()) {
                                                            if (deviceParam.getTechDeviceParamFillType() == 4 || deviceParam.getTechDeviceParamFillType() == 5) {
                                                                // 忽略
                                                                deviceParamType.getTechDeviceParamList().remove(deviceParam);
                                                                break;
                                                            } else {
                                                                if (deviceParamType.getTechDeviceParamTypeId().equals(techDeviceParamTypeId) && techDeviceParam.getTechDeviceParamNameCn().equals(deviceParam.getTechDeviceParamNameCn())) {
                                                                    if (CommonUtils.isNumeric(deviceParam.getTechDeviceParamDeclareValue()) && CommonUtils.isNumeric(v7)) {
                                                                        if (Double.parseDouble(deviceParam.getTechDeviceParamDeclareValue()) == Double.parseDouble(v7)) {
                                                                            deviceParamType.getTechDeviceParamList().remove(deviceParam);
                                                                        } else {
                                                                            needSubmitNums++;
                                                                            deviceParam.setTechDeviceOriginParamDeclareValue(deviceParam.getTechDeviceParamDeclareValue());
                                                                            deviceParam.setTechDeviceParamDeclareValue(CommonUtils.removeZeros(v7));
                                                                            deviceParam.setSubmitTechDeviceParamDeclareValue(CommonUtils.removeZeros(v7));
                                                                        }
                                                                    } else {
                                                                        if (deviceParam.getTechDeviceParamDeclareValue() == null || "".equals(deviceParam.getTechDeviceParamDeclareValue()) || v7 == null || "".equals(v7)) {
                                                                            if (deviceParam.getTechDeviceParamDeclareValue() == null || "".equals(deviceParam.getTechDeviceParamDeclareValue())) {
                                                                                needSubmitNums++;
                                                                                deviceParam.setTechDeviceOriginParamDeclareValue("");
                                                                                deviceParam.setTechDeviceParamDeclareValue(CommonUtils.removeZeros(v7));
                                                                                deviceParam.setSubmitTechDeviceParamDeclareValue(CommonUtils.removeZeros(v7));
                                                                            } else {
                                                                                needSubmitNums++;
                                                                                deviceParam.setTechDeviceOriginParamDeclareValue(deviceParam.getTechDeviceParamDeclareValue());
                                                                                deviceParam.setTechDeviceParamDeclareValue("");
                                                                                deviceParam.setSubmitTechDeviceParamDeclareValue("");
                                                                            }
                                                                        } else {
                                                                            if (deviceParam.getTechDeviceParamDeclareValue() != null && deviceParam.getTechDeviceParamDeclareValue().equals(v7)) {
                                                                                deviceParamType.getTechDeviceParamList().remove(deviceParam);
                                                                            } else {
                                                                                needSubmitNums++;
                                                                                deviceParam.setTechDeviceOriginParamDeclareValue(deviceParam.getTechDeviceParamDeclareValue());
                                                                                deviceParam.setTechDeviceParamDeclareValue(CommonUtils.removeZeros(v7));
                                                                                deviceParam.setSubmitTechDeviceParamDeclareValue(CommonUtils.removeZeros(v7));
                                                                            }
                                                                        }
                                                                    }
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                        JSONObject jo = new JSONObject();
                                        jo.put("data", techDeviceParamTypeList);
                                        jo.put("pcbaDeviceTypeId", pcbaDeviceTypeId);
                                        jo.put("pcbaDeviceTypeName", pcbaDeviceTypeName);
                                        jo.put("brandId", brandId);
                                        jo.put("brandName", brandName);
                                        jo.put("brandTypeId", brandTypeId);
                                        jo.put("brandTypeName", brandTypeName);
                                        jo.put("notes", notes);

                                        jsonObject.put("index", a + 1);
                                        jsonObject.put("result", "success");
                                        jsonObject.put("message", "这个要执行update");
                                        jsonObject.put("data", jo);
                                        jsonObject.put("action", "update");
                                        jsonObject.put("needSubmitNums", needSubmitNums);
                                    }
                                } else {
                                    if (pcbaDeviceResourceList.size() > 1) {
                                        jsonObject.put("index", a + 1);
                                        jsonObject.put("result", "fail");
                                        jsonObject.put("message", "找到多个 设备类型+品牌+型号+备注 的设备资源，请添加备注后尝试重新导入");
                                        jsonObject.put("action", "");
                                    } else {
                                        jsonObject.put("index", a + 1);
                                        jsonObject.put("result", "fail");
                                        jsonObject.put("message", "没有找到对应 设备类型+品牌+型号+备注 的设备资源");
                                        jsonObject.put("action", "");
                                    }
                                }
                            }
                        }
                    } else {
                        jsonObject.put("index", a + 1);
                        jsonObject.put("result", "fail");
                        jsonObject.put("message", "数据为空");
                        jsonObject.put("action", "");
                    }
                } else {
                    jsonObject.put("index", a + 1);
                    jsonObject.put("result", "fail");
                    jsonObject.put("message", "模板不正确(建议：修改对应sheet模板)");
                    jsonObject.put("action", "");
                }
                list.add(jsonObject);
            }
            return ResultUtil.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result submitImportTechDeviceResourcesData(String data) {
        try {
            List<PcbaDeviceRelatedTechParam> oldPcbaDeviceRelatedTechParamList = new ArrayList<>();
            List<PcbaDeviceRelatedTechParam> newPcbaDeviceRelatedTechParamList = new ArrayList<>();
            Date d = new Date();
            String userId = UserHeaderHolder.getUserId();
            JSONArray jsonArray = JSONArray.parseArray(data);
            for (int a = 0; a < jsonArray.size(); a++) {
                JSONObject jsonObject = jsonArray.getJSONObject(a);
                String result = jsonObject.get("result") != null ? jsonObject.get("result").toString() : "";
                String needSubmitNums = jsonObject.get("needSubmitNums") != null ? jsonObject.get("needSubmitNums").toString() : "";
                String action = jsonObject.get("action") != null ? jsonObject.get("action").toString() : "";

                if ("success".equals(result)) {
                    String resourceDataStr = jsonObject.get("data").toString();
                    JSONObject resourceJo = JSONObject.parseObject(resourceDataStr);
                    String brandId = resourceJo.get("brandId").toString();
                    String brandTypeId = resourceJo.get("brandTypeId").toString();
                    String notes = resourceJo.get("notes").toString();
                    String pcbaDeviceTypeId = resourceJo.get("pcbaDeviceTypeId").toString();
                    if ("update".equals(action)) {
                        // update
                        if (Integer.parseInt(needSubmitNums) > 0) {
                            // update
                            PcbaDeviceResource pcbaDeviceResource = pcbaDeviceResourceDao.getByConditionsJudgeUnique(Integer.parseInt(pcbaDeviceTypeId), Integer.parseInt(brandId), Integer.parseInt(brandTypeId), notes, null);
                            if (pcbaDeviceResource != null) {
                                Integer pcbaDeviceResourceId = pcbaDeviceResource.getPcbaDeviceResourceId();

                                // 设备资源的 工艺审核状态修改为 待提交审核
                                pcbaDeviceResourceDao.updateAuditStatusTechWithSubmitter(pcbaDeviceResourceId, 4, Integer.parseInt(userId));

                                JSONArray paramsDataJa = resourceJo.getJSONArray("data");
                                for (int c = 0; c < paramsDataJa.size(); c++) {
                                    JSONObject paramsDataJo = paramsDataJa.getJSONObject(c);

                                    JSONArray paramsListJa = paramsDataJo.getJSONArray("techDeviceParamList");
                                    for (int b = 0; b < paramsListJa.size(); b++) {
                                        JSONObject jo = paramsListJa.getJSONObject(b);
                                        String techDeviceParamKey = jo.getString("techDeviceParamKey");
                                        String submitTechDeviceParamDeclareValue = jo.getString("submitTechDeviceParamDeclareValue");

                                        PcbaDeviceRelatedTechParam pcbaDeviceRelatedTechParam = pcbaDeviceRelatedTechParamDao.getPcbaDeviceRelatedTechParamByKeyAndDeviceResourceId(techDeviceParamKey, pcbaDeviceResourceId);
                                        if (pcbaDeviceRelatedTechParam != null) {
                                            // update
                                            oldPcbaDeviceRelatedTechParamList.add(pcbaDeviceRelatedTechParam);

                                            PcbaDeviceRelatedTechParam updatePcbaDeviceRelatedTechParam = new PcbaDeviceRelatedTechParam();
                                            updatePcbaDeviceRelatedTechParam.setPcbaDeviceRelatedTechParamId(pcbaDeviceRelatedTechParam.getPcbaDeviceRelatedTechParamId());
                                            updatePcbaDeviceRelatedTechParam.setTechDeviceParamValue(submitTechDeviceParamDeclareValue);
                                            updatePcbaDeviceRelatedTechParam.setUpdateTime(d);
                                            pcbaDeviceRelatedTechParamDao.updateDeviceRelatedParam(updatePcbaDeviceRelatedTechParam);

                                            newPcbaDeviceRelatedTechParamList.add(updatePcbaDeviceRelatedTechParam);
                                        } else {
                                            // insert
                                            PcbaDeviceRelatedTechParam addPcbaDeviceRelatedTechParam = new PcbaDeviceRelatedTechParam();
                                            addPcbaDeviceRelatedTechParam.setPcbaDeviceResourceId(pcbaDeviceResourceId);
                                            addPcbaDeviceRelatedTechParam.setTechDeviceParamKey(techDeviceParamKey);
                                            addPcbaDeviceRelatedTechParam.setPcbaDeviceTypeId(Integer.parseInt(pcbaDeviceTypeId));
                                            addPcbaDeviceRelatedTechParam.setTechDeviceParamValue(submitTechDeviceParamDeclareValue);
                                            addPcbaDeviceRelatedTechParam.setCreateTime(d);
                                            pcbaDeviceRelatedTechParamDao.addDeviceRelatedParam(addPcbaDeviceRelatedTechParam);

                                            newPcbaDeviceRelatedTechParamList.add(addPcbaDeviceRelatedTechParam);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // 操作日志
            if (oldPcbaDeviceRelatedTechParamList.size() > 0 || newPcbaDeviceRelatedTechParamList.size() > 0) {
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 2, d, JSONObject.toJSONString(oldPcbaDeviceRelatedTechParamList), JSONObject.toJSONString(newPcbaDeviceRelatedTechParamList)));
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result auditPcbaDeviceResource(Integer pcbaDeviceResourceId, Integer auditStatusBase, String auditRemarkBase) {
        try {
            if (pcbaDeviceResourceId == null || "".equals(pcbaDeviceResourceId.toString())) {
                return ResultUtil.error(500, "缺少参数pcbaDeviceResourceId", "Miss Param pcbaDeviceResourceId", null);
            }
            String userId = UserHeaderHolder.getUserId();
            Integer integer = pcbaDeviceResourceDao.updateAuditStatusBaseWithAuditor(pcbaDeviceResourceId, auditStatusBase, auditRemarkBase, Integer.parseInt(userId));
            if (integer > 0) {

                List<JSONObject> changeList = new ArrayList<>();
                List<PcbaDeviceRelatedDeviceParam> l = pcbaDeviceRelatedDeviceParamDao.getAllByDeviceResourceId(pcbaDeviceResourceId);
                for (PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam : l) {
                    if (pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValueAudit() != null && pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValue() != null && !pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValueAudit().equals(pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValue())) {
                        PcbaDeviceParam pcbaDeviceParam = pcbaDeviceParamDao.getPcbaDeviceParamByKey(pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamKey());
                        JSONObject j = new JSONObject();
                        j.put("key", pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamKey());
                        j.put("label", pcbaDeviceParam != null ? pcbaDeviceParam.getPcbaDeviceParamNameCn() : "");
                        j.put("oldValue", pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValueAudit());
                        j.put("newValue", pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValue());
                        changeList.add(j);
                    }
                }

               /* <p>1、如果`审核通过`，则会触发以下联动</p>
          <div>&nbsp;&nbsp;&nbsp;1）则将修改能力值覆盖到最终能力值</div>
          <div>&nbsp;&nbsp;&nbsp;2）若发生变动的能力项涉及到工艺资源池的联动，则需要联动修改工艺资源池的值，如果最终有值发生变化，则需将工艺资源池的状态修改为`待提交审核`，否则不会引发工艺资源池的联动</div>
          <div>&nbsp;&nbsp;&nbsp;3）若发生变动的能力项涉及到基线整线能力的联动，则需要联动修改基线整线能力的值</div>
          <div>&nbsp;&nbsp;&nbsp;4）若3）中发生变动的基线整线能力项关联到工艺整线宣称能力，则需要联动修改工艺整线宣称能力，并将工艺整线宣称能力的状态修改为待确认</div>
          <p>2、如果`审核不通过`，则会触发以下联动</p>
          <div>&nbsp;&nbsp;&nbsp;1）则将能力值还原，并且不会引发其他联动</div>*/
                if (auditStatusBase == 1) {
                    // 审核通过，将 valueAudit 的值清空
                    pcbaDeviceRelatedDeviceParamDao.clearValueAudit(pcbaDeviceResourceId);

                    // 添加 auditRecord 状态追踪
//                    AuditRecord addAuditRecord = new AuditRecord(
//                            1,  pcbaDeviceResourceId,  1,  Integer.parseInt(userId),  JSON.toJSONString(changeList),  auditRemarkBase,  null,  new Date(),  new Date()
//                    );
//                    auditRecordDao.addAuditRecord(addAuditRecord);

                    // 2）若发生变动的能力项涉及到工艺资源池的联动，则需要联动修改工艺资源池的值，如果最终有值发生变化，则需将工艺资源池的状态修改为`待提交审核`，否则不会引发工艺资源池的联动
                    if (changeList.size() > 0) {
                        for (JSONObject jsonObject : changeList) {
                            String pcbaDeviceParamKey = jsonObject.getString("key");
                            List<TechDeviceParam> techDeviceParamList = techDeviceParamDao.getTechDeviceParamByBindKey(pcbaDeviceParamKey);
                            for (TechDeviceParam techDeviceParam : techDeviceParamList) {
                                Integer techDeviceParamFillType = techDeviceParam.getTechDeviceParamFillType();
                                String bindDeviceParamKey = techDeviceParam.getBindDeviceParamKey();
                                String techDeviceParamKey = techDeviceParam.getTechDeviceParamKey();
                                if (techDeviceParamFillType == 4) {
                                    // 来自基线
                                    PcbaDeviceRelatedDeviceParam pdrdp = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(bindDeviceParamKey, pcbaDeviceResourceId);
                                    PcbaDeviceRelatedTechParam pdrtp = pcbaDeviceRelatedTechParamDao.getPcbaDeviceRelatedTechParamByKeyAndDeviceResourceId(techDeviceParamKey, pcbaDeviceResourceId);
                                    if (pdrdp != null && pdrtp != null) {
                                        String pcbaDeviceParamValue = pdrdp.getPcbaDeviceParamValue();
                                        String techDeviceParamValue = pdrtp.getTechDeviceParamValue();
                                        if (!pcbaDeviceParamValue.equals(techDeviceParamValue)) {
                                            pdrtp.setPcbaDeviceRelatedTechParamId(pdrtp.getPcbaDeviceRelatedTechParamId());
                                            pdrtp.setTechDeviceParamValue(pcbaDeviceParamValue);
                                            pdrtp.setTechDeviceParamValueAudit(techDeviceParamValue);
                                            pcbaDeviceRelatedTechParamDao.updateDeviceRelatedParam(pdrtp);

                                            // 修改工资资源池状态 待提交审核
                                            pcbaDeviceResourceDao.updateAuditStatusTechWithSubmitter(pcbaDeviceResourceId, 4, Integer.parseInt(userId));
                                        }
                                    }
                                }
                                if (techDeviceParamFillType == 5) {
                                    // 取多个基线最小值
                                    List<String> valueList = new ArrayList<>();
                                    String[] split = bindDeviceParamKey.split(",");
                                    for (String k : split) {
                                        PcbaDeviceRelatedDeviceParam pdrdp = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(k, pcbaDeviceResourceId);
                                        if (pdrdp != null && pdrdp.getPcbaDeviceParamValue() != null) {
                                            valueList.add(pdrdp.getPcbaDeviceParamValue());
                                        }
                                    }
                                    // 计算最小值
                                    String minV = "99999999999";
                                    for (String s : valueList) {
                                        if (CommonUtils.isNumeric(s)) {
                                            double currentValue = Double.parseDouble(s);
                                            if (currentValue < Double.parseDouble(minV)) {
                                                minV = Double.toString(currentValue);
                                            }
                                        }
                                    }
                                    if ("99999999999".equals(minV)) {
                                        minV = "";
                                    }
                                    PcbaDeviceRelatedTechParam pdrtp = pcbaDeviceRelatedTechParamDao.getPcbaDeviceRelatedTechParamByKeyAndDeviceResourceId(techDeviceParamKey, pcbaDeviceResourceId);
                                    if (pdrtp != null && !"".equals(minV)) {
                                        String techDeviceParamValue = pdrtp.getTechDeviceParamValue();
                                        if (!minV.equals(techDeviceParamValue)) {
                                            pdrtp.setPcbaDeviceRelatedTechParamId(pdrtp.getPcbaDeviceRelatedTechParamId());
                                            pdrtp.setTechDeviceParamValue(minV);
                                            pdrtp.setTechDeviceParamValueAudit(techDeviceParamValue);
                                            pcbaDeviceRelatedTechParamDao.updateDeviceRelatedParam(pdrtp);

                                            // 修改工资资源池状态 待提交审核
                                            pcbaDeviceResourceDao.updateAuditStatusTechWithSubmitter(pcbaDeviceResourceId, 4, Integer.parseInt(userId));
                                        }
                                    }
                                }
                            }
                        }

                        // 3）若发生变动的能力项涉及到基线整线能力的联动，则需要联动修改基线整线能力的值
                        // 4）工艺宣称能力是否确认状态改为`待确认`
                        // 重新计算基线资源所在线体的基线能力
                        List<PcbaDevice> pcbaDeviceList = pcbaDeviceDao.getPcbaDeviceResourceByPcbaDeviceResourceId(pcbaDeviceResourceId);
                        List<Integer> pcbaLineIdList = new ArrayList<>();
                        for (PcbaDevice pcbaDevice : pcbaDeviceList) {
                            Integer pcbaLineId = pcbaDevice.getPcbaLineId();
                            if (!pcbaDeviceList.contains(pcbaLineId)) {
                                pcbaLineIdList.add(pcbaLineId);
                            }
                        }
                        if (pcbaLineIdList.size() > 0) {
                            for (Integer lineId : pcbaLineIdList) {
                                // 计算了整线基线能力并保存到数据库
                                coreAlgorithmService.calcLineBaseCapacity(lineId);
                                pcbaLineDao.updatePcbaLineLockDeclare(lineId, 2);
                            }
                        }
                    }
                }
                if (auditStatusBase == 2) {
                    // 审核不通过，将 value 的值还原成 valueAudit 的值
                    pcbaDeviceRelatedDeviceParamDao.returnValueFromValueAudit(pcbaDeviceResourceId);

                    // 添加 auditRecord 状态追踪
//                    AuditRecord addAuditRecord = new AuditRecord(
//                            1,  pcbaDeviceResourceId,  2,  Integer.parseInt(userId),  JSON.toJSONString(changeList),  auditRemarkBase,  null,  new Date(),  new Date()
//                    );
//                    auditRecordDao.addAuditRecord(addAuditRecord);
                }

                // 级联触发 线体的最终状态
                coreAlgorithmService.cascadeUpdateLineFinalStatus(1, pcbaDeviceResourceId, null, null);

                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result auditTechDeviceResource(Integer pcbaDeviceResourceId, Integer auditStatusTech, String auditRemarkTech) {
        try {
            if (pcbaDeviceResourceId == null || "".equals(pcbaDeviceResourceId.toString())) {
                return ResultUtil.error(500, "缺少参数pcbaDeviceResourceId", "Miss Param pcbaDeviceResourceId", null);
            }
            String userId = UserHeaderHolder.getUserId();
            Integer integer = pcbaDeviceResourceDao.updateAuditStatusTechWithAuditor(pcbaDeviceResourceId, auditStatusTech, auditRemarkTech, Integer.parseInt(userId));
            if (integer > 0) {

                List<JSONObject> changeList = new ArrayList<>();
                List<PcbaDeviceRelatedTechParam> l = pcbaDeviceRelatedTechParamDao.getAllByDeviceResourceId(pcbaDeviceResourceId);
                for (PcbaDeviceRelatedTechParam pcbaDeviceRelatedTechParam : l) {
                    if (!pcbaDeviceRelatedTechParam.getTechDeviceParamValueAudit().equals(pcbaDeviceRelatedTechParam.getTechDeviceParamValue())) {
                        TechDeviceParam techDeviceParam = techDeviceParamDao.getTechDeviceParamByKey(pcbaDeviceRelatedTechParam.getTechDeviceParamKey());
                        JSONObject j = new JSONObject();
                        j.put("key", pcbaDeviceRelatedTechParam.getTechDeviceParamKey());
                        j.put("label", techDeviceParam != null ? techDeviceParam.getTechDeviceParamNameCn() : "");
                        j.put("oldValue", pcbaDeviceRelatedTechParam.getTechDeviceParamValueAudit());
                        j.put("newValue", pcbaDeviceRelatedTechParam.getTechDeviceParamValue());
                        j.put("actualEqualDeclare", techDeviceParam != null ? techDeviceParam.getActualEqualDeclare() : "2");
                        changeList.add(j);
                    }
                }

                /*<p>1、如果`审核通过`，则会触发以下联动</p>
          <div>&nbsp;&nbsp;&nbsp;1）则将修改能力值覆盖到最终能力值【已完成】</div>
          <div>&nbsp;&nbsp;&nbsp;2）若发生变动的能力项关联设备实际工艺能力并且引起变更，则需要将设备实际工艺能力值联动修改，并且状态修改为`待提交审核`，否则无需联动【已完成】</div>
          <p>2、如果`审核不通过`，则会触发以下联动</p>
          <div>&nbsp;&nbsp;&nbsp;1）则将能力值还原，并且不会引发其他联动【已完成】</div>*/

                if (auditStatusTech == 1) {
                    // 审核通过，将 valueAudit 的值清空
                    pcbaDeviceRelatedTechParamDao.clearValueAudit(pcbaDeviceResourceId);

                    // 需额外增加判断，若当前设备的实际认证能力是‘认证通过’，则记录下审核值
                    List<PcbaDevice> list = pcbaDeviceDao.getPcbaDeviceResourceByPcbaDeviceResourceId(pcbaDeviceResourceId);
                    for (PcbaDevice pcbaDevice : list) {
                        if(pcbaDevice.getParamsStatus() != null && pcbaDevice.getParamsStatus() == 1){
                            pcbaDeviceRelatedTechParamActualDao.returnValueAuditFromValue(pcbaDevice.getPcbaDeviceId());
                        }
                    }

                    // 2）若发生变动的能力项关联设备实际工艺能力并且引起变更，则需要将设备实际工艺能力值联动修改，并且状态修改为`待提交审核`，否则无需联动
                    if (changeList.size() > 0) {
                        for (JSONObject jsonObject : changeList) {
                            String actualEqualDeclare = jsonObject.getString("actualEqualDeclare");
                            String techDeviceParamKey = jsonObject.getString("key");
                            String newValue = jsonObject.getString("newValue");
                            TechDeviceParam tdp = techDeviceParamDao.getTechDeviceParamByKey(techDeviceParamKey);
                            if ("1".equals(actualEqualDeclare) && tdp != null) {
                                List<PcbaDevice> pcbaDeviceList = pcbaDeviceDao.getPcbaDeviceResourceByPcbaDeviceResourceId(pcbaDeviceResourceId);
                                for (PcbaDevice pcbaDevice : pcbaDeviceList) {
                                    Integer currentParamsStatus = pcbaDevice.getParamsStatus();
                                    PcbaDeviceRelatedTechParamActual pdrtpa = pcbaDeviceRelatedTechParamActualDao.getPcbaDeviceRelatedTechParamActualByPcbaDeviceIdAndKey(pcbaDevice.getPcbaDeviceId(), techDeviceParamKey);
                                    if (pdrtpa != null) {
                                        Integer pcbaDeviceRelatedTechParamActualId = pdrtpa.getPcbaDeviceRelatedTechParamActualId();
                                        String techDeviceParamValue = pdrtpa.getTechDeviceParamValue();
                                        String techDeviceParamValueAudit = pdrtpa.getTechDeviceParamValueAudit();
                                        if (techDeviceParamValueAudit != null) {
                                            if (!newValue.equals(techDeviceParamValue)) {
                                                pdrtpa.setPcbaDeviceRelatedTechParamActualId(pcbaDeviceRelatedTechParamActualId);
                                                pdrtpa.setTechDeviceParamValue(newValue);
                                                pdrtpa.setTechDeviceParamValueAudit(techDeviceParamValueAudit);
                                                pdrtpa.setUpdateTime(new Date());
                                                pcbaDeviceRelatedTechParamActualDao.updateDeviceRelatedParamActual(pdrtpa);

                                                // 修改设备实际工艺能力 待提交审核
                                                pcbaDevice.setParamsStatus(4);
                                                pcbaDeviceDao.updatePcbaDevice(pcbaDevice);
                                            }
                                        } else {
                                            if (!newValue.equals(techDeviceParamValue)) {
                                                pdrtpa.setPcbaDeviceRelatedTechParamActualId(pcbaDeviceRelatedTechParamActualId);
                                                pdrtpa.setTechDeviceParamValue(newValue);
                                                pdrtpa.setTechDeviceParamValueAudit(techDeviceParamValue);
                                                pdrtpa.setUpdateTime(new Date());
                                                pcbaDeviceRelatedTechParamActualDao.updateDeviceRelatedParamActual(pdrtpa);

                                                // 修改设备实际工艺能力 待提交审核
                                                pcbaDevice.setParamsStatus(4);
                                                pcbaDeviceDao.updatePcbaDevice(pcbaDevice);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
                if (auditStatusTech == 2) {
                    // 审核不通过，将 value 的值还原成 valueAudit 的值
                    pcbaDeviceRelatedTechParamDao.returnValueFromValueAudit(pcbaDeviceResourceId);
                }

                // 级联触发 线体的最终状态
                coreAlgorithmService.cascadeUpdateLineFinalStatus(1, pcbaDeviceResourceId, null, null);

                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result addResourceByExcel(String data) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String newNotes = jsonObject.getString("newNotes") != null ? jsonObject.getString("newNotes") : "";
            JSONObject deviceInfoJo = jsonObject.getJSONObject("deviceInfo");
            String pcbaDeviceTypeId = deviceInfoJo.getString("pcbaDeviceTypeId");
            String brandId = deviceInfoJo.getString("brandId");
            String brandTypeId = deviceInfoJo.getString("brandTypeId");
            JSONArray pcbaDeviceParamTypeList = jsonObject.getJSONArray("pcbaDeviceParamTypeList");
            List<PcbaDeviceResource> pcbaDeviceResourceList = pcbaDeviceResourceDao.getByConditions(Integer.parseInt(pcbaDeviceTypeId), Integer.parseInt(brandId), Integer.parseInt(brandTypeId), null, null);
            List<String> notesList = new ArrayList<>();
            for (PcbaDeviceResource pcbaDeviceResource : pcbaDeviceResourceList) {
                notesList.add(pcbaDeviceResource.getNotes());
            }
            if (notesList.contains(newNotes)) {
                return ResultUtil.error(500, "当前设备资源已存在，换个备注试试吧", "Already Exist", null);
            }
            Date d = new Date();
            // 新增设备资源 ，状态改为 待提交审核4
            PcbaDeviceResource addPcbaDeviceResource = new PcbaDeviceResource();
            addPcbaDeviceResource.setPcbaDeviceTypeId(Integer.parseInt(pcbaDeviceTypeId));
            addPcbaDeviceResource.setBrandId(Integer.parseInt(brandId));
            addPcbaDeviceResource.setBrandTypeId(Integer.parseInt(brandTypeId));
            addPcbaDeviceResource.setCreateTime(d);
            addPcbaDeviceResource.setStatus(1);
            addPcbaDeviceResource.setSort(100);
            addPcbaDeviceResource.setNotes(newNotes);
            addPcbaDeviceResource.setIsFilledBaseParams(2);
            addPcbaDeviceResource.setIsFilledTechParams(2);
            addPcbaDeviceResource.setAuditStatusBase(4);
            addPcbaDeviceResource.setAuditStatusBase(4);
            pcbaDeviceResourceDao.addPcbaDeviceResource(addPcbaDeviceResource);
            // 新增基线资源参数
            Integer pcbaDeviceResourceId = addPcbaDeviceResource.getPcbaDeviceResourceId();

            PcbaDeviceRelatedDeviceParam addPcbaDeviceRelatedDeviceParam = new PcbaDeviceRelatedDeviceParam();
            for (int a = 0; a < pcbaDeviceParamTypeList.size(); a++) {
                JSONArray pcbaDeviceParamList = pcbaDeviceParamTypeList.getJSONObject(a).getJSONArray("pcbaDeviceParamList");
                for (int b = 0; b < pcbaDeviceParamList.size(); b++) {
                    String pcbaDeviceParamKey = pcbaDeviceParamList.getJSONObject(b).getString("pcbaDeviceParamKey");
                    String pcbaDeviceParamValue = pcbaDeviceParamList.getJSONObject(b).getString("pcbaDeviceParamValue");
                    addPcbaDeviceRelatedDeviceParam.setPcbaDeviceResourceId(pcbaDeviceResourceId);
                    addPcbaDeviceRelatedDeviceParam.setPcbaDeviceParamKey(pcbaDeviceParamKey);
                    addPcbaDeviceRelatedDeviceParam.setPcbaDeviceTypeId(Integer.parseInt(pcbaDeviceTypeId));
                    addPcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValue(pcbaDeviceParamValue);
                    addPcbaDeviceRelatedDeviceParam.setCreateTime(d);
                    pcbaDeviceRelatedDeviceParamDao.addDeviceRelatedParam(addPcbaDeviceRelatedDeviceParam);
                }
            }

            return ResultUtil.success(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result coverResourceByExcel(String data) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String pcbaDeviceResourceId = jsonObject.getString("pcbaDeviceResourceId");
            JSONArray needCoverResource = jsonObject.getJSONArray("needCoverResource");
            if (pcbaDeviceResourceId == null || "".equals(pcbaDeviceResourceId)) {
                return ResultUtil.error(500, "缺少参数pcbaDeviceResourceId", "Miss Param pcbaDeviceResourceId", null);
            }
            Date d = new Date();
            String userId = UserHeaderHolder.getUserId();
            for (int a = 0; a < needCoverResource.size(); a++) {
                JSONArray pcbaDeviceParamList = needCoverResource.getJSONObject(a).getJSONArray("pcbaDeviceParamList");
                String pcbaDeviceTypeId = needCoverResource.getJSONObject(a).getString("pcbaDeviceTypeId");
                String pcbaDeviceParamTypeId = needCoverResource.getJSONObject(a).getString("pcbaDeviceParamTypeId");
                for (int b = 0; b < pcbaDeviceParamList.size(); b++) {
                    String pcbaDeviceParamKey = pcbaDeviceParamList.getJSONObject(b).getString("pcbaDeviceParamKey");
                    String submitPcbaDeviceParamValue = pcbaDeviceParamList.getJSONObject(b).getString("submitPcbaDeviceParamValue");

                    // 查询 关联表是否存在，存在update  不存在 insert
                    PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(pcbaDeviceParamKey, Integer.parseInt(pcbaDeviceResourceId));
                    if (pcbaDeviceRelatedDeviceParam == null) {
                        // insert
                        PcbaDeviceRelatedDeviceParam addPcbaDeviceRelatedDeviceParam = new PcbaDeviceRelatedDeviceParam();
                        addPcbaDeviceRelatedDeviceParam.setPcbaDeviceResourceId(Integer.parseInt(pcbaDeviceResourceId));
                        addPcbaDeviceRelatedDeviceParam.setPcbaDeviceParamKey(pcbaDeviceParamKey);
                        addPcbaDeviceRelatedDeviceParam.setPcbaDeviceTypeId(Integer.parseInt(pcbaDeviceTypeId));
                        addPcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValue(submitPcbaDeviceParamValue);
                        addPcbaDeviceRelatedDeviceParam.setCreateTime(d);
                        pcbaDeviceRelatedDeviceParamDao.addDeviceRelatedParam(addPcbaDeviceRelatedDeviceParam);
                    } else {
                        // update
                        Integer pcbaDeviceRelatedDeviceParamId = pcbaDeviceRelatedDeviceParam.getPcbaDeviceRelatedDeviceParamId();
                        PcbaDeviceRelatedDeviceParam updatePcbaDeviceRelatedDeviceParam = new PcbaDeviceRelatedDeviceParam();
                        updatePcbaDeviceRelatedDeviceParam.setPcbaDeviceResourceId(Integer.parseInt(pcbaDeviceResourceId));
                        updatePcbaDeviceRelatedDeviceParam.setPcbaDeviceParamKey(pcbaDeviceParamKey);
                        updatePcbaDeviceRelatedDeviceParam.setPcbaDeviceTypeId(Integer.parseInt(pcbaDeviceTypeId));
                        updatePcbaDeviceRelatedDeviceParam.setPcbaDeviceParamValue(submitPcbaDeviceParamValue);
                        updatePcbaDeviceRelatedDeviceParam.setUpdateTime(d);
                        updatePcbaDeviceRelatedDeviceParam.setPcbaDeviceRelatedDeviceParamId(pcbaDeviceRelatedDeviceParamId);
                        pcbaDeviceRelatedDeviceParamDao.updateDeviceRelatedParam(updatePcbaDeviceRelatedDeviceParam);
                    }
                }
            }

            // 将 设备资源 的 基线认证状态变成  待提交审核
            // 并触发以下联动
            //   1）当前设备资源的工艺资源池认证状态变动，改为待提交审核
            PcbaDeviceResource updatePcbaDeviceResource = new PcbaDeviceResource();
            updatePcbaDeviceResource.setUpdateTime(d);
            updatePcbaDeviceResource.setAuditStatusBase(4);
            updatePcbaDeviceResource.setAuditStatusTech(4);
            updatePcbaDeviceResource.setPcbaDeviceResourceId(Integer.parseInt(pcbaDeviceResourceId));
            pcbaDeviceResourceDao.updatePcbaDeviceResource(updatePcbaDeviceResource);
            //   2）当前设备资源对应的设备工艺实际能力认证状态变动，改为待提交审核
            List<Integer> pLineIdList = new ArrayList<>();
            List<PcbaDevice> pdList = pcbaDeviceDao.getPcbaDeviceResourceByPcbaDeviceResourceId(Integer.parseInt(pcbaDeviceResourceId));
            for (PcbaDevice pcbaDevice : pdList) {
                if (pcbaDevice.getParamsStatus() != null && pcbaDevice.getParamsStatus() == 1) {
                    pcbaDeviceDao.updatePcbaDeviceParamsStatus(pcbaDevice.getPcbaDeviceId(), 4);
                }

                // 构造应用到此设备的线体
                Integer pcbaLineId = pcbaDevice.getPcbaLineId();
                if (!pLineIdList.contains(pcbaLineId)) {
                    pLineIdList.add(pcbaLineId);
                }
            }

            //   3）使用到该设备资源的线体的基线审核状态不变；工艺审核状态改为待提交审核
            for (Integer plId : pLineIdList) {
                PcbaLine oldPLine = pcbaLineDao.getPcbaLineById(plId);
                /*if(oldPLine != null && oldPLine.getParamsStatusBase() != null && oldPLine.getParamsStatusBase() == 1){
                    pcbaLineDao.auditPcbaLineParamBase(plId, 4, "");
                }*/
                if (oldPLine != null && oldPLine.getParamsStatusActual() != null && oldPLine.getParamsStatusActual() == 1) {
                    pcbaLineDao.auditPcbaLineParamTechActual(plId, 4, "");
                }
            }


            return ResultUtil.success(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
}
